让我有程序打开文件并附加一些东西。 如果我应该运行两个apllication,我将获得另一个进程使用的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");
}
}
}
答案 0 :(得分:3)
您应该尝试打开并写入该文件。如果它正在使用,你会得到一个例外。在.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;
}