我们有一个Windows Forms应用程序,该应用程序连接到某些Web服务。它列出了系统中的文档,当用户双击文档时,我们将文件下载到本地计算机,然后打开文档进行编辑。用户关闭文档后,我们会将其上传回系统。
在此过程中,我们一直在监视文档上的文件锁定。释放文件锁后,我们就会上载文档。
该IsFileLocked方法如下所示:
private const int ErrorLockViolation = 33;
private const int ErrorSharingViolation = 32;
private static bool IsFileLocked(string fileName)
{
Debug.Assert(!string.IsNullOrEmpty(fileName));
try
{
if (File.Exists(fileName))
{
using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
fs.ReadByte();
}
}
return false;
}
catch (IOException ex)
{
// get the HRESULT for this exception
int errorCode = Marshal.GetHRForException(ex) & 0xFFFF;
return errorCode == ErrorSharingViolation || errorCode == ErrorLockViolation;
}
}
Run Code Online (Sandbox Code Playgroud)
我们将其称为循环,两次尝试之间有5秒钟的睡眠时间。在大多数情况下,这似乎效果很好,但有时我们会IOException从这种方法中看到一个。我看不到有可能引发此异常。
例外是:
IOException: The process cannot …Run Code Online (Sandbox Code Playgroud)