让我们看一下这个代码示例:
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()
..这是意料之中且显而易见的。但是, IOException 的实例并没有为我提供任何可靠的信息,我可以使用这些信息以编程方式检测文件是否正在被另一个进程使用。只是Message
物业告诉你,但这取决于当地文化,所以我不能依赖它。
知道如何处理吗?如果文件正在被另一个进程使用,我需要采取特殊措施,但我找不到将这种情况与其他(异常)情况分开的方法。