10

I have a C# application and I want to copy a file to a new location. Some times I need to overwrite an existing file. when this happens I receive a System.IO.IOException. I want to recover from a Sharing violation but how do I determine that IOException was returned because the destination file is in use rather then some other reason? I could look for the "The process cannot access the file because it is being used by another process." message... But I don't like that idea.

3 Answers 3

8

This was the solution I came up with.

private void RobustMoveFile( System.IO.DirectoryInfo destinationDirectory, System.IO.FileInfo sourceFile, Boolean retryMove )
                {
                    try
                    {
                        string DestinationFile = Path.Combine( destinationDirectory.FullName, sourceFile.Name );
                        if ( File.Exists( DestinationFile ) )
                            sourceFile.Replace( DestinationFile, DestinationFile + "Back", true );
                        else
                        {
                            sourceFile.CopyTo( DestinationFile, true );
                            sourceFile.Delete();
                        }
                    }
                    catch ( System.IO.IOException IOEx )
                    {
                        int HResult = System.Runtime.InteropServices.Marshal.GetHRForException( IOEx );        
                        const int SharingViolation = 32;
                        if ( ( HResult & 0xFFFF ) == SharingViolation && retryMove )
                            RobustMoveFile( destinationDirectory, sourceFile, false );
                        throw;
                    }
                }
1
  • 1
    No need to check for destination file existence, as some other process may create/delete it between the check and the replace/CopyTo operations. Just change your logic that you always create the detination file no matter what, and if this fails, recover or retry. Jan 9, 2009 at 15:12
3

As other answers have stated, you need to get the HResult of the error and check it. An HResult of 0x80070020 is a sharing violation. The last two bytes of the HResult are the code, for a sharing violation the code is 0x0020 = 32.

In .NET 4.5, the IOException has a public HResult property, so you can just do as follows:

try
{
    // do file IO here
}
catch (IOException e)
{
    if ((e.HResult & 0xFFFF) == 32) // 32 = Sharing violation
    {
        // Recovery logic goes here
    }
    else
    {
        throw; // didn't need to catch this
    }
}

In earlier versions of .NET, however, you need to get the HResult by calling Marshal.GetHRForException(Exception), so the similar code would be:

try
{
    // do file IO here
}
catch (IOException e)
{
    int HResult = System.Runtime.InteropServices.Marshal.GetHRForException(e)
    if ((HResult & 0xFFFF) == 32) // 32 = Sharing violation
    {
        // Recovery logic goes here
    }
    else
    {
        throw; // Or do whatever else here
    }
}

C# 6.0 allows you to use this syntax to catch only a sharing violation with a when clause:

try
{
    // do file IO here
}
catch (IOException e) when ((e.HResult & 0xFFFF) == 32) // 32 = Sharing violation
{
    // Recovery logic goes here
}
0
-3

Look for the explicit error codes that you can deal with, for example:

catch (Exception u) { if (((SocketException)u).ErrorCode == 10035) ...

Take a look here: http://msdn.microsoft.com/en-us/library/ms681391(VS.85).aspx

for error codes, e.g.:

ERROR_SHARING_VIOLATION - 32 - 0x20

ERROR_ACCESS_DENIED = 5 - 0x5

ERROR_FILE_NOT_FOUND - 2 - 0x2

2
  • How will the cast from IOException to SocketException will succeed? Jan 8, 2009 at 21:53
  • just an example... didn't think it would throw anyone off
    – cookre
    Jan 9, 2009 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.