1

在我的 C# 代码中,我大致有这个:

    public void RunCommand()
    {
        var processStartInfo = new ProcessStartInfo(
            "notepad.exe")
        {
            UseShellExecute = true,
            Verb = "Runas",
        };
        var process = Process.Start(processStartInfo);
        process.WaitForExit(1000);
    }

运行时,这会提示用户授予提升的权限。如果用户拒绝,调用将引发Win32Exception,并带有文本“操作已被用户取消”。

我想专门捕捉这个异常,即将它与其他异常区分开来。我希望能够知道用户已取消。

我可以有理由相信,当抛出Win32Exception时,它可能是这样的吗?或者由于各种其他原因,调用会抛出Win32Exception吗?我不想开始对错误消息进行字符串匹配,因为这可能会因用户设置而异......

4

1 回答 1

1

我最终这样做了,这似乎适用于我的系统:

    public void RunCommand()
    {
        var processStartInfo = new ProcessStartInfo(
            "notepad.exe")
        {
            UseShellExecute = true,
            Verb = "Runas",
        };
        var process = Process.Start(processStartInfo);
        process.WaitForExit(1000);
    }
    catch (Win32Exception e)
    {
        if (e.ErrorCode == 1223 || e.ErrorCode == -2147467259)
            // Throw easily recognizable custom exception.
            throw new ElevatedPermissionsDeniedException("Unable to get elevated privileges", e);
        else
            throw;
    }
于 2020-01-22T11:37:43.880 回答