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

And*_*nea 4 .net c# io process 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

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

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

Chr*_*n.K 12

这个问题是可能的重复一个,更何况这里的答案非常接近接受一个.但是,要检查的错误代码存在一些显着差异.最后,您可能会考虑对另一个问题的答案进行评价.

你可以在这个答案中做,但检查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.
}
Run Code Online (Sandbox Code Playgroud)

但是,你要知道,使用GetHRForException副作用,你可能不希望有.

更新为评论者@jmn2指出,自.NET 4.5以来,该Exception.HResult属性现已公开.所以没有必要使用GetHRForException- 当然,除非你需要支持4.5之前的代码.

要写出一个"包装",即运行时的向后兼容,你应该调用HResult通过反射,因为(只要你使用GetPropertiesBindingFlags.Public BindingFlags.NonPublic),将与.NET Framework的所有版本(见这个有很大关系的答案).