模拟文件锁定时在 C# 中等待 File.Open
本质上,我有与此海报相同的问题,但在 C# 中: 等待文件可供 Win32 读取
更多信息:我们的一个项目中有调用 File.Open
的代码,当文件已经存在时,该代码偶尔会终止由另一个进程(编辑:或线程)打开:
FileStream stream = File.Open(m_fileName, m_mode, m_access);
/* do stream-type-stuff */
stream.Close();
File.Open
将抛出一个IOException
(目前正在悄悄地被某处吞噬),其< code>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();
但是,HResult
是 Exception
的受保护成员,并且无法访问 - 代码不编译。是否有另一种方法可以访问 HResult
,或者可能是我可以用来执行我想要的操作的 .NET 的另一部分?
哦,最后一个警告,这很奇怪:我仅限于使用 Visual Studio 2005 和 .NET 2.0。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
catch
子句中调用Marshal.GetHRForException()
来获取错误代码。无需反思:You can call
Marshal.GetHRForException()
within thecatch
clause to get the error code. No need for reflection:不幸的是,你最好的选择是使用反射。当然,由于您在两次尝试之间休眠 1 秒,因此性能成本很可能不会被注意到。
Your best bet is using reflection unfortunately. Of course, since you sleep for 1sec between attempts, the performance costs will most likely go unnoticed.