- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们有一个连接到某些网络服务的 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/
我的 blockly.js 文件中有以下代码 Blockly.Blocks['account_number'] = { // Other type. init: function() {
首先抱歉我的英语不好,我正在开发 Image Splitter 应用程序并且已经完成,但是现在的要求是当图像被分割(分成几 block /chunks)那么图像 block 的每一 block (ch
#value: 消息的返回值,当发送到一个 block 时,是该 block 中最后一句话的值。所以 [ 1 + 2. 3 + 4. ] value 计算结果为 7。我发现有时很难使用。有没有办法显式
我想构建一个包含 3 div 的响应式导航栏相同的 width和 height . 我申请了 inline-block到每个 block ,我得到一个我不理解的行为。 问题是,第三 block 由 2
我希望使用 Blockly 来允许非技术人员用户指定测试脚本。 它的一部分需要一个文件选择器,但是,我看不到 Blockly 有一个。是吗? 实际上,我找不到完整的标准 block 列表。谁有网址?
仅当您位于父 block 内部时,父 block 的 props.isSelected 才为 true,但当您在该 block 的 innerBlocks 内进行编辑时则不然。 如何从父 block
仅当您位于父 block 内部时,父 block 的 props.isSelected 才为 true,但当您在该 block 的 innerBlocks 内进行编辑时则不然。 如何从父 block
我想创建一个具有不同背景颜色 block 和不同悬停颜色 block 的导航栏 block 。我可以分别创建不同的悬停颜色 block 或不同的背景颜色 block ,但不能一起创建。所以请告诉我如何
我正在使用看到的代码 here定期执行代码: #define DELAY_IN_MS 1000 __block dispatch_time_t next = dispatch_time(DISPATC
为什么 block 必须被复制而不是保留?两者在引擎盖下有什么区别?在什么情况下不需要复制 block (如果有)? 最佳答案 通常,当您分配一个类的实例时,它会进入堆并一直存在,直到它被释放。但是,
我想弄清楚我这样做是否正确: 如果我有一个 block ,我会这样做: __weak MyClass *weakSelf = self; [self performBlock:^{
我想制作一个 4 block 导航菜单,虽然我已经显示了一个 block ,然后单击打开第二个 block ,从第二个开始选择并再次单击出现第三个 block ,第四个 block 相同...这是我的
例如,这样更好吗? try { synchronized (bean) { // Write something } } catch (Int
我想让一只乌龟检查前方小块的颜色并决定移动到哪里。如果前面的补丁不是白色的,那么乌龟向左或向右旋转并移动。我的 If 决策结构中出现错误,显示“此处应为 TRUE?FALSE,而不是 block 列表
我想创建一个 block 对角矩阵,其中对角 block 重复一定次数,非对角 block 都是零矩阵。例如,假设我们从一个矩阵开始: > diag.matrix [,1] [,2] [
我是区 block 链新手。突然我有一个问题,我们是否可以通过区 block 号来访问以太坊区 block 链上之前的区 block 数据。 例如我创建了一个block1、block2。 block
我是区 block 链新手。突然我有一个问题,我们是否可以通过区 block 号来访问以太坊区 block 链上之前的区 block 数据。 例如我创建了一个block1、block2。 block
我创建了一个等距环境,全部使用 Javascript 和 HTML5 (2D Canvas),大部分情况下工作正常。我面临的问题是使用不同高度的图 block ,然后对图 block 上的对象索引进行
这是令我困惑的代码: public Integer getInteger(BlockingQueue queue) { boolean interrupted = false; try
我有一个基于 TPL 数据流的应用程序,它仅使用批处理 block 和操作 block 就可以正常工作。 我已经添加了一个 TransformBlock 以尝试在发布到批处理 block 之前从源中转
我是一名优秀的程序员,十分优秀!