C#检查进程使用的文件

C# check file that used by process

让我有一个程序可以打开文件并附加一些东西。 如果我应该 运行 两个应用程序,我将得到另一个进程使用的 IOException 文件。如何检查另一个进程正在使用文件 Log.txt?

class Program
{
    static void Main(string[] args)
    {
        FileInfo file = new FileInfo(@"D:\Log.txt");
        using (StreamWriter sw = file.AppendText())
        {
            for (int i = 0; i < 1000; i++)
            {
                System.Threading.Thread.Sleep(100);
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
            Console.WriteLine("The work is done");
        }
    }
}

您应该尝试打开并写入文件。如果它正在使用中,你会得到一个例外。在 .NET 中没有其他方法。

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}