开发者

errorCode for The process cannot access the file 'XYZ' because it is being used by another process

I using C# .NET , vs 2008 , .net 3.5

For me, is diffic开发者_运维问答ult, but I need sample code in C# for this:

  1. How get the error code of IOException "The process cannot access the file 'XYZ' because it is being used by another process."

For example, in my issue.

I try delete file, and I get "The process cannot access the file 'XYZ' because it is being used by another process." Exception.

try
{
    File.Delete(infoFichero.Ruta);
}
catch (IOException ex)
{
    // ex.Message == "The process cannot access the file 'XYZ' because it is being used by another process."
}

But if .NET is Spanish, I get "El proceso no puede obtener acceso al archivo '00000004.PDF' porque está siendo utilizado en otro proceso" message.

System.IO.IOException: El proceso no puede obtener acceso al archivo '00000004.PDF' porque está siendo utilizado en otro proceso.
   en System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   en System.IO.FileInfo.Delete()

I need a ERROR CODE for that Exception. In Trace, I have seen System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

How get the error code of IOException "The process cannot access the file 'XYZ' because it is being used by another process."


You might have noticed that the HResult property is not accessible. The workaround is to use the Marshal.GetLastWin32Error() method to get the native Windows error code. Like this:

        catch (IOException ex) {
            int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
            if (err == 32) Console.WriteLine("It's locked");
            // etc..
        }

Error code 32 is named ERROR_SHARING_VIOLATION in the SDK.


there's an HResult property on (IO-)Exception that contains an error code. According to this list the error code for your exception should be 0x20 (I didn't try that though). Hope that helps.


(marked CW because this is really just an extended comment)

Why do you need the error code?

  • Are you going to take a different action based on one code versus another code?
  • What will you do if Windows or .NET changes, so that you're suddenly getting a different error code back for the same problem?
  • What do you want to do if you can't delete the same file, but for a different reason? In fact, maybe your new problem won't even throw an IOException.


Have a look at the HRESULT property of the IOException class. This should return the Win32 HRESULT of the operation (which is what I think you're looking for?).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜