gpt4 book ai didi

c# - 模拟文件锁定时在 C# 中等待 File.Open

转载 作者:太空狗 更新时间:2023-10-29 21:25:18 25 4
gpt4 key购买 nike

本质上,我遇到了与这张海报相同的问题,但在 C# 中:Waiting until a file is available for reading with Win32

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

FileStream stream = File.Open(m_fileName, m_mode, m_access);
/* do 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);
}
}
/* do stream-type-stuff */
stream.Close();

但是,HResultException 的 protected 成员,无法访问——代码无法编译。是否有另一种访问 HResult 的方法,或者我可以用来做我想做的事情的 .NET 的另一部分?

哦,最后一个警告,这是一个愚蠢的问题:我仅限于使用 Visual Studio 2005 和 .NET 2.0。

最佳答案

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

using System.Runtime.InteropServices;

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

关于c# - 模拟文件锁定时在 C# 中等待 File.Open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3138483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com