Take this code example:
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 is trying to overwrite) throws an exception:
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()
.. what is expected and obvious. HOWEVER , an instance of IOException does not offer me any reliable information that I can use programmatically to detect that a file is being used by another process. The Message property simply reports this, but it depends on the local culture, so I cannot rely on it.
Any ideas how to deal with this? I need to do a special action if the file is used by another process, but I canโt find a way to separate this case from other (exceptional) cases.