Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8435173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T06:50:50+00:00 2026-06-10T06:50:50+00:00

Let’s take this code sample : using System; using System.IO; namespace ConsoleApplication25 { class

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T06:50:51+00:00Added an answer on June 10, 2026 at 6:50 am

    This question is possible a duplicate of this one, more so the answer here is pretty close to the accepted one. However, there is some notable difference about the error codes to check. You might consider, eventually, upvoting the answer to the other question.

    You could do as in this answer, but check for 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.
    }
    

    However, mind you that using GetHRForException has side effects you may not want to have.

    Update As commenter @jmn2 pointed out, since .NET 4.5 the Exception.HResult property is now public. So there is no need for using GetHRForException – unless you need to support pre 4.5 code, of course.

    To write a “wrapper” that is runtime-backwards compatible you should invoke HResult via reflection because (provided you use GetProperties with BindingFlags.Public and BindingFlags.NonPublic) that will work with all versions of the .NET framework (see this very much related answer).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

let's say we have some simple code like this : private static void Main()
Let's say on a page I have alot of this repeated: <div class=entry> <h4>Magic:</h4>
Let's say I have this code: <p dataname=description> Hello this is a description. <a
Let's suppose I have this piece of code. foreach(string value in myList) { string
Let's say I have the following function in C#: void ProcessResults() { using (FormProgress
Let's use the code from the first section of this website. I don't see
Let me explain best with an example. Say you have node class that can
Let's say I have a sortable list like this: $(.song-list).sortable({ handle : '.pos_handle', axis
Let's say I have a string like this: var str = /abcd/efgh/ijkl/xxx-1/xxx-2; How do
Let's say I can call a method like this: core::get() . What is the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.