我有一个应用程序,有时我需要从正在写入的文件中读取结果被锁定。正如我从其他人那里了解到的questions我应该捕获 IOException 并重试,直到我可以阅读。
但我的问题是我如何确定该文件已被锁定并且它不是发生的另一个 IOExcetpion。
最佳答案
当您在 .NET 中打开文件进行读取时,它会在某个时候尝试使用 CreateFile 创建文件句柄设置 error code 的 API 函数可以用来查看它失败的原因:
const int ERROR_SHARING_VIOLATION = 32;
try
{
using (var stream = new FileStream("test.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
{
}
}
catch (IOException ex)
{
if (Marshal.GetLastWin32Error() == ERROR_SHARING_VIOLATION)
{
Console.WriteLine("The process cannot access the file because it is being used by another process.");
}
}
关于c# - 如何最好地等待文件锁释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/690242/