c# - 如何最好地等待文件锁释放

标签 c# .net ioexception filelock

我有一个应用程序,有时我需要从正在写入的文件中读取结果被锁定。正如我从其他人那里了解到的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/

相关文章:

android - dex文件安卓: unable to open DEX file

c# - 为什么 callvirt IL 指令会导致虚方法中的递归调用?

c# - ASP.Net MVC 长时间运行的进程

.net - 使用Visual Studio 2012生成数据库脚本

.net - 无效的产品版本 'a.b.cd.xy' 。格式必须为 '##.##.####' 。如何将默认版本格式更改为具有 3 个小数点

c# - Entity Framework 继承 - 仅检索父类型

java - 文件.createNewFile() IOException "No such file or directory"

java - Apache Axis 库

c# - 如何将多个列表与 Lambda 表达式相交?

c# - 异常 : Parameter is not valid (on passing new image to pictureBox)