如何判断IOException是否是由另一个进程使用该文件引起的?

时间:2012-08-21 12:29:27

标签: c# .net process io ioexception

我们来看看这段代码:

using System;
using System.IO;

namespace ConsoleApplication25
{
    class Program
    {
        static void Main()
        {
            var bytes = new byte[] { 1, 2, 3 };
            var trimChars = new[] { '"' };
            var path = Environment.CommandLine.Trim().Trim(trimChars);
            File.WriteAllBytes(path, bytes);
        }
    }
}

运行此程序(程序试图覆盖自身)会导致抛出异常:

System.IO.IOException was unhandled
Message=The process cannot access the file 'F:\TEMP\ConsoleApplication25\ConsoleApplication25\bin\Debug\ConsoleApplication25.vshost.exe' because it is being used by another process.
Source=mscorlib
StackTrace:
   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)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
   at ConsoleApplication25.Program.Main() in F:\TEMP\ConsoleApplication25\ConsoleApplication25\Program.cs:line 13
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

..这是预期和明显的。 HOWEVER ,IOException实例没有向我提供任何可靠信息,我可以使用以编程方式来检测文件是否正在使用另一个过程。只有Message属性告诉你这个,但这取决于当地的文化,所以我不能依赖它。

知道怎么处理这个吗?如果该文件正由另一个进程使用,我需要采取特殊操作,但我找不到将这种情况与其他(例外)情况分开的方法。

2 个答案:

答案 0 :(得分:12)

这个问题可能是this一个的重复,因此这里的答案非常接近accepted one。但是,要检查的错误代码存在一些显着差异。最后,你可能会考虑对另一个问题的答案进行评价。

您可以在this回答中执行,但请检查ERROR_SHARING_VIOLATION(0x20)

const long ERROR_SHARING_VIOLATION = 0x20;
const long ERROR_LOCK_VIOLATION = 0x21;

//Only for .NET <4.5: long win32ErrorCode = Marshal.GetHRForException(ex) & 0xFFFF;
long win32ErrorCode = ex.HResult & 0xFFFF; // .NET 4.5+
if (win32ErrorCode == ERROR_SHARING_VIOLATION || win32ErrorCode == ERROR_LOCK_VIOLATION )
{
    // file in use.
}

但是,请注意,使用GetHRForException时您可能不希望拥有side effects

更新正如评论者@jmn2指出的那样,自.NET 4.5起,Exception.HResult属性现已公开。因此,除非您需要支持4.5之前的代码,否则无需使用GetHRForException

要编写与运行时向后兼容的“包装器”,您应该通过反射调用HResult因为(假设您使用GetProperties {BindingFlags.Public {1}})将适用于所有版本的.NET框架(请参阅this very much related answer)。

答案 1 :(得分:1)

这是similar question

您需要检查异常的HResult。然后检查它的值:

int hr = Marshal.GetHRForException( ex );

以下是锁定违规的sharing violation代码

相关问题