Search code examples
c#windowsasync-awaitprocessadmin-rights

How to run a process asynchronously in administration mode?


I need my app to require admin rights before running a process asynchronously. It used to work well with the following configuration in the app.manifest:

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

However, since now processes were added that should not require admin rights to be run, this elegant solution no longer cuts it. I expected this to do the trick:

process.StartInfo.UseShellExecute = true;
process.StartInfo.Verb = "runas";

This is what I have, but there must be an error somewhere, since this code runs the process as expected, but doesn't actually require admin rights to do so:

public async Task ExecuteElevatedProcessAsync(string executablePathArg)
{
    using (var process = new Process())
    {
        process.StartInfo.FileName = executablePathArg;
        process.StartInfo.UseShellExecute = true;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.Verb = "runas";
        await RunAsync(process);
    };
}

private Task RunAsync(Process processArg)
{
    var taskCompletionSrc = new TaskCompletionSource<object>();
    processArg.EnableRaisingEvents = true;
    processArg.Exited += (s, e) => taskCompletionSrc.TrySetResult(null);
    if (!processArg.Start())
    {
        taskCompletionSrc.SetException(new Exception("Some descriptive error-message."));
    }
    return taskCompletionSrc.Task;
}

Do you know how to fix this?


Solution

  • By running it on another computer I’ve learned that the above code does indeed work as intended: Before executing the asynchronous process, it triggers the Windows UAC-popup that asks the user to give the app permission to make changes to the device.

    The popup was never triggered on my Windows machine because the user account control was disabled entirely, which isn’t a smart choice to begin with...