处理由Process.Start()引发的Win32Exception

3

在某些电脑上,当我调用Process.Start()来启动我的辅助可执行文件时,我会收到以下异常:

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

问题:当我遇到Win32Exception异常时,我想知道这是我描述的“文件未找到”异常还是其他异常。如何可靠地做到这一点?我应该将这个0x80004005与某些内容进行比较,还是应该解析错误消息?
一些解释:由于某种原因,可执行文件可能会被删除(这就是为什么会出现文件未找到的情况)。这是一个预期的情况。如果异常是由其他原因引起的,我想报告它。

1
0x80004005E_FAIL。这个错误代码过于泛化,不太有帮助。你可能会在 NativeErrorCode 中找到更好的解决方法。 - GSerg
1个回答

6
我认为应该这样做:

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 是一个 HRESULT 值ERROR_FILE_NOT_FOUND 是一个 系统错误代码

不应使用这个错误消息,因为它是与文化相关的,实际上是系统错误代码的翻译。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接