【问题标题】:C#: How to catch the exception when user refuses to grant elevated privileges?C#:当用户拒绝授予提升的权限时如何捕获异常?
【发布时间】:2020-01-21 09:46:29
【问题描述】:

在我的 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 吗?我不想在错误消息上开始字符串匹配,因为这可能会因用户设置而异......

【问题讨论】:

  • 看来你已经尝试过了。为什么要改变异常类型?如果失败了,失败的原因真的很重要吗?如果notepad.exe 不可用,我可以考虑其他问题,例如 FileNotFound。
  • 我不希望异常类型更改,但我希望此调用可能会由于各种其他原因引发Win32Exception。因此,如果我捕获 Win32Exception,我不确定这是因为用户取消了。
  • 检查Win32Exception.ErrorCode是否为1223确定。
  • 有一个宏可以将 Win32 错误映射到 HRESULT。它可能在已经链接的文档中(如果您有兴趣)

标签: c# exception uac win32exception


【解决方案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;
    }

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 2021-12-21
    • 2016-09-12
    • 2012-03-07
    • 1970-01-01
    • 2016-03-16
    • 2011-10-17
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多