进程使用的C#检查文件
让我有打开文件并追加内容的程序。 如果我应该运行两个apllication,我会得到另一个进程使用的IOException文件。如何检查Log.txt文件正在被另一个进程使用?进程使用的C#检查文件
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;
}
这是正确的:当某些进程可以从文件中读/写时,任何可能的测试和实际写入文件之间存在*时间差*。 –
如果你打算使用别人的答案它的好形式包括一个链接到他们的帖子http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-正在使用 – MikeT
@MikeT答案是我的,我提供的代码已被用于其他答案的事实是无关紧要的,因为如果您在stackoverflow或谷歌搜索,你会发现在1000年的文章中使用完全相同的代码。 ..那么,谁是主人?您提供的链接是否是从某处复制的其他用户?无果而无意义的辩论,对不起。 – sam
是否要检查_if_文件是否被另一个进程使用,或者您想检查_what_进程是否正在使用它? –
@VisualVincent,我想检查一下情况。 – A191919
然后Try/Catch是您的解决方案。萨姆提供了一个很好的答案。 –