当文件被锁定时,模拟在C#中的File.Open等待

Bla*_*way 6 c# file-io filestream ioexception .net-2.0

基本上,我和这张海报有同样的问题,但是在C#中:等待文件可以用Win32读取

更多信息:我们的代码调用File.Open了我们的一个项目,当文件已被另一个进程(EDIT:或线程)打开时偶尔会死掉:

FileStream stream = File.Open(m_fileName, m_mode, m_access);
/* do stream-type-stuff */
stream.Close();
Run Code Online (Sandbox Code Playgroud)

File.Open将抛出IOException(目前在某处悄悄吞下),其HResult属性为0x80070020(ERROR_SHARING_VIOLATION).我会喜欢做的是这样的:

FileStream stream = null;
while (stream == null) {
    try {
        stream = File.Open(m_fileName, m_mode, m_access, FileShare.Read);
    } catch (IOException e) {
        const int ERROR_SHARING_VIOLATION = int(0x80070020);
        if (e.HResult != ERROR_SHARING_VIOLATION)
            throw;
        else
            Thread.Sleep(1000);
    }
}
/* do stream-type-stuff */
stream.Close();
Run Code Online (Sandbox Code Playgroud)

但是,HResult是受保护的成员Exception,并且无法访问 - 代码无法编译.有没有另一种方法可以访问HResult.NET,或者可能是另一部分我可能会用来做我想要的东西?

哦,最后一个警告,这是一个doozy:我只能使用Visual Studio 2005和.NET 2.0.

Iga*_*nik 8

您可以Marshal.GetHRForException()catch子句中调用以获取错误代码.无需反思:

using System.Runtime.InteropServices;

if (Marshal.GetHRForException(e) == ERROR_SHARING_VIOLATION)
    ....
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`Marshal.GetExceptionCode()`是错的,现在我已经看到它正在运行.我真正需要的是'Marshal.GetHRForException(e)`.你介意更新你的答案吗? (2认同)