Code Pyre

All Code Dies and Burns in Time

Fork me on GitHub

Running an Elevated Child Process

| Comments

If you ever need to run a child process in an elevated state, you can easily set the Verbs property on the ProcessStartInformation to “runas” and the child process will ask for permission when started. You need to watch out the the user denying access however as a Win32Exception will be thrown with its NativeErrorCode = 1223. Here is a simple example launching the admin command prompt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
internal class Program
{
    private const int UserCanceled = 1223;

    private static void Main( string[] args )
    {
        var psInfo = new ProcessStartInfo
                     {
                         FileName = Environment.GetEnvironmentVariable ("ComSpec"),
                         UseShellExecute = true,
                         Verb = ( Environment.OSVersion.Version.Major >= 6 ) ? "runas" : string.Empty
                     };

        try
        {
            Process process = Process.Start( psInfo );
            Console.WriteLine( "Process has Id: {0}", process.Id );
            Console.WriteLine( "Waiting for app to exit." );
            process.WaitForExit();
        }
        catch ( Win32Exception ex )
        {
            if ( ex.NativeErrorCode != UserCanceled )
            {
                throw;
            }
            // permission was denied.
            Console.WriteLine( "The operation was canceled by the user." );
        }

        Console.WriteLine( "App exited, press enter to exit." );
        Console.ReadLine();
    }
}

Comments