Search code examples
c#exceptionuacwin32exception

C#: How to catch the exception when user refuses to grant elevated privileges?


In my C# code I have roughly this:

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

When run, this prompts the user to grant elevated privileges. If the user refuses, the call throws a Win32Exception with the text "The operation was cancelled by the user".

I want to catch this exception specifically, i.e., tell it apart from other exceptions. I want to be able to know that the user has cancelled.

Can I be reasonably confident that when a Win32Exception is thrown, it is probably this? Or can the call throw Win32Exception for all sorts of other reasons? I don't want to start string matching on the error message, since that presumably varies depending on user settings...


Solution

  • I ended up doing this, which seems to work on my system:

        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;
        }