Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Win32Exception thrown by Process.Start()

Tags:

c#

.net

winapi

On some computers, when I call Process.Start() to start my helper executable, I get the following exception:

System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()

The question: when I get Win32Exception, I want to tell if this is the "file not found" exception I described or something else. How to do this reliably? Should I compare this 0x80004005 against something, or should I parse the error message?

Some explanation: the executable may get removed by for some reason (that's why file not found). This is an expected situation. If the exception was thrown with some other reason, I want to report it.

like image 522
Andrey Moiseev Avatar asked Aug 15 '26 15:08

Andrey Moiseev


1 Answers

This is how, I believe, it should be done:

public static int E_FAIL = unchecked((int)0x80004005);
public static int ERROR_FILE_NOT_FOUND = 0x2;

// When the exception is caught

catch (Win32Exception e)
{
    if(e.ErrorCode == E_FAIL && e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
    {
    // This is a "File not found" exception
    }
    else
    {
    // This is something else
    }
}

E_FAIL is a HRESULT value, ERROR_FILE_NOT_FOUND is a system error code.

The error message shouldn't be used because it is culture-dependent and is actually a translation of the system error code.

like image 83
Andrey Moiseev Avatar answered Aug 17 '26 05:08

Andrey Moiseev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!