gpt4 book ai didi

c# - 尽管 IOException catch block 引发了 IOException

转载 作者:行者123 更新时间:2023-12-03 19:39:09 27 4
gpt4 key购买 nike

我们有一个连接到某些网络服务的 Windows 窗体应用程序。它列出了系统中的文档,当用户双击一个文件时,我们将文件下载到本地计算机并打开文档供他们编辑。一旦用户关闭文档,我们就会将其上传回系统。

对于这个过程,我们一直在监控文档上的文件锁。一旦文件锁定被释放,我们就会上传文档。

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

我们在尝试之间有 5 秒休眠的循环中调用它。这似乎在大多数情况下都很有效,但偶尔我们会看到此方法的 IOException。我看不出为什么会抛出这个异常。

异常(exception)情况是:

IOException: The process cannot access the file 'C:\Users\redacted\AppData\Roaming\redacted\Jobs\09c39a4c-c1a3-4bb9-a5b5-54e00bb6c747\4b5c4642-8ede-4881-8fa9-a7944852d93e\CV abcde abcdef.docx' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at redacted.Helpers.IsFileLocked(String fileName)
at System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, IntPtr reserved, Object& ppunk)
at System.Runtime.InteropServices.Marshal.GetActiveObject(String progID)
at redacted.OutlookHelper.GetOutlookInternal()
at redacted.OutlookHelper.GetOutlook()
...

另一个奇怪的部分是堆栈跟踪。这指的是 GetOutlook,它是系统的一个完全不同的部分(与文档处理无关)。 IsFileLocked 有两个代码路径,并且都无法通过 GetOutlookInternal 方法访问。这几乎就像堆栈正在损坏一样。

为什么不使用 FileSystemWatcher ?

作为旁注,我们确实考虑过使用 FileSystemWatcher 来监视文件更改,但不考虑这种方法,因为用户可能会保持文档打开并继续对其进行进一步更改。我们的网络服务会在我们上传文件后立即解锁该文件,因此在用户完成它之前我们无法解锁。

我们只关心被其应用程序锁定的文档。我很欣赏有些应用程序不会锁定其文件,但我们不需要在这里考虑它们。

Outlook 方法

下面是堆栈中出现的 GetOutlookInternal 方法 - 如您所见,它只处理 Outlook Interop,与文档打开无关。它不会调用 IsFileLocked:

    private static Application GetOutlookInternal()
{
Application outlook;

// Check whether there is an Outlook process running.
if (Process.GetProcessesByName("OUTLOOK").Length > 0)
{
try
{
// If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
outlook = (Application)Marshal.GetActiveObject("Outlook.Application");
}
catch (COMException ex)
{
if (ex.ErrorCode == -2147221021) // HRESULT: 0x800401E3 (MK_E_UNAVAILABLE)
{
// Outlook is running but not ready (not in Running Object Table (ROT) - http://support.microsoft.com/kb/238610)
outlook = CreateOutlookSingleton();
}
else
{
throw;
}
}
}
else
{
// If not running, create a new instance of Outlook and log on to the default profile.
outlook = CreateOutlookSingleton();
}
return outlook;
}

private static Application CreateOutlookSingleton()
{
Application outlook = new Application();

NameSpace nameSpace = null;
Folder folder = null;
try
{
nameSpace = outlook.GetNamespace("MAPI");

// Create an instance of the Inbox folder. If Outlook is not already running, this has the side
// effect of initializing MAPI. This is the approach recommended in http://msdn.microsoft.com/en-us/library/office/ff861594(v=office.15).aspx
folder = (Folder)nameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
}
finally
{
Helpers.ReleaseComObject(ref folder);
Helpers.ReleaseComObject(ref nameSpace);
}

return outlook;
}

最佳答案

我无意中发现这篇文章有助于找到问题的原因:Marshal.GetHRForException does more than just Get-HR-For-Exception

事实证明我们有两个线程,一个正在调用 Marshal.GetHRForException(...)IOException 上确定文件是否被锁定(Win32 错误代码 32 或 33)。另一个线程正在调用 Marshal.GetActiveObject(...)使用 Interop 连接到 Outlook 实例。

如果首先调用 GetHRForException,然后调用 GetActiveObject 但抛出 COMException,那么您将得到完全错误的异常和堆栈痕迹。这是因为 GetHRForException 有效地“设置”了异常,而 GetActiveObject 将抛出该异常,而不是真正的 COMException

要重现的示例代码:

可以使用以下代码重现此问题。创建一个新的控制台应用程序,导入 Outlook COM 引用,然后粘贴代码。启动应用程序时确保 Outlook 未运行:

    public static void Main(string[] args)
{
bool isLocked = IsFileLocked();
Console.WriteLine("IsLocked = " + isLocked);
ShowOutlookWindow();
}

private static bool IsFileLocked()
{
try
{
using (FileStream fs = File.Open(@"C:\path\to\non_existant_file.docx", FileMode.Open, FileAccess.Read, FileShare.None))
{
fs.ReadByte();
return false;
}
}
catch (IOException ex)
{
int errorCode = Marshal.GetHRForException(ex) & 0xFFFF;
return errorCode == 32 || errorCode == 33; // lock or sharing violation
}
}

private static void ShowOutlookWindow()
{
try
{
Application outlook = (Application)Marshal.GetActiveObject("Outlook.Application");
// ^^ causes COMException because Outlook is not running
MailItem mailItem = outlook.CreateItem(OlItemType.olMailItem);
mailItem.Display();
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
throw;
}
}

您希望在控制台中看到 COMException,但这是您所看到的

IsLocked = False
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\path\to\non_existant_file.docx'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.Open(String path, FileMode mode, FileAccess access, FileShare share)
at MyProject.Program.IsFileLocked()
at System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, IntPtr reserved, Object& ppunk)
at System.Runtime.InteropServices.Marshal.GetActiveObject(String progID)
at MyProject.Program.ShowOutlookWindow()

请注意异常是 DirectoryNotFoundException,堆栈错误地建议 GetActiveObject 调用 IsFileLocked

解决方案:

解决这个问题的方法很简单,就是使用 Exception.HResult属性而不是 GetHRForException。以前此属性受到保护,但现在可以访问,因为我们将项目升级到 .NET 4.5

private static bool IsFileLocked()
{
try
{
using (FileStream fs = File.Open(@"C:\path\to\non_existant_file.docx", FileMode.Open, FileAccess.Read, FileShare.None))
{
fs.ReadByte();
return false;
}
}
catch (IOException ex)
{
int errorCode = ex.HResult & 0xFFFF;
return errorCode == 32 || errorCode == 33; // lock or sharing violation
}
}

通过此更改,行为符合预期。控制台现在显示:

IsLocked = False
System.Runtime.InteropServices.COMException (0x800401E3): Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))
at System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, IntPtr reserved, Object& ppunk)
at System.Runtime.InteropServices.Marshal.GetActiveObject(String progID)
at MyProject.Program.ShowOutlookWindow()

TL;DR:如果您还使用 COM 组件,请不要使用 Marshal.GetHRForException

关于c# - 尽管 IOException catch block 引发了 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37120825/

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