Let's take this code sample :
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);
}
}
}
running this (the program tries to overwrite itself) causes an exception to be thrown :
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()
.. which is expected and obvious. HOWEVER, the instance of the IOException doesn't offer me any reliable information that I can use programatically to detect that the file is in use by another process. Just the Message
property tells you this, but this depends on the local culture so I can't rely on it.
Any idea how to deal with this? I need to take a special action if the file is in use by another process but I can't find a way to separate this case from other (exceptional) cases.