当文件被锁定时,在C#中模拟等待File.Open [英] Emulate waiting on File.Open in C# when file is locked

查看:1063
本文介绍了当文件被锁定时,在C#中模拟等待File.Open的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我本质上和这张海报有相同的问题,但是在C#中:等待,直到一个文件可用于阅读与Win32



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

  FileStream stream = File.Open(m_fileName,m_mode,m_access); 
/ *做stream-type-stuff * /
stream.Close();

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);


做stream-type-stuff * /
stream.Close();

但是, HResult 是受保护的成员 Exception ,无法访问 - 代码不能编译。有没有另外一种方式来访问 HResult ,或者也许是我可以用来做我想要的.NET的另一部分?



哦,最后一个警告,这是一个愚蠢的:我只能使用Visual Studio 2005和.NET 2.0。 解决方案

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

  using System.Runtime.InteropServices; 

if(Marshal.GetHRForException(e)== ERROR_SHARING_VIOLATION)
....


I have, essentially, the same problem as this poster, but in C#: Waiting until a file is available for reading with Win32

More information: we have code that calls File.Open in one of our projects, that occasionally dies when the file is already opened by another process (EDIT: or thread):

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

File.Open will throw an IOException (which is currently quietly swallowed somewhere), whose HResult property is 0x80070020 (ERROR_SHARING_VIOLATION). What I would like to do is this:

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();

However, HResult is a protected member of Exception, and cannot be accessed -- the code does not compile. Is there another way of accessing the HResult, or perhaps, another part of .NET I might use to do what I want?

Oh, one final caveat, and it's a doozy: I'm limited to using Visual Studio 2005 and .NET 2.0.

解决方案

You can call Marshal.GetHRForException() within the catch clause to get the error code. No need for reflection:

using System.Runtime.InteropServices;

if (Marshal.GetHRForException(e) == ERROR_SHARING_VIOLATION)
    ....

这篇关于当文件被锁定时,在C#中模拟等待File.Open的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆