To run cmd as administrator along with command?

As @mtijn said you’ve got a lot going on that you’re also overriding later. You also need to make sure that you’re escaping things correctly.

Let’s say that you want to run the following command elevated:

dir c:\

First, if you just ran this command through Process.Start() a window would pop open and close right away because there’s nothing to keep the window open. It processes the command and exits. To keep the window open we can wrap the command in separate command window and use the /K switch to keep it running:

cmd /K "dir c:\"

To run that command elevated we can use runas.exe just as you were except that we need to escape things a little more. Per the help docs (runas /?) any quotes in the command that we pass to runas need to be escaped with a backslash. Unfortunately doing that with the above command gives us a double backslash that confused the cmd parser so that needs to be escaped, too. So the above command will end up being:

cmd /K \"dir c:\\\"

Finally, using the syntax that you provided we can wrap everything up into a runas command and enclose our above command in a further set of quotes:

runas /env /user:Administrator "cmd /K \"dir c:\\\""

Run the above command from a command prompt to make sure that its working as expected.

Given all that the final code becomes easier to assemble:

        //Assuming that we want to run the following command:
        //dir c:\

        //The command that we want to run
        string subCommand = @"dir";

        //The arguments to the command that we want to run
        string subCommandArgs = @"c:\";

        //I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
        //Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
        string subCommandFinal = @"cmd /K \""" + subCommand.Replace(@"\", @"\\") + " " + subCommandArgs.Replace(@"\", @"\\") + @"\""";

        //Run the runas command directly
        ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
        procStartInfo.UseShellExecute = true;
        procStartInfo.CreateNoWindow = true;

        //Create our arguments
        string finalArgs = @"/env /user:Administrator """ + subCommandFinal + @"""";
        procStartInfo.Arguments = finalArgs;

        //command contains the command to be executed in cmd
        using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
        {
            proc.StartInfo = procStartInfo;
            proc.Start();
        }

Leave a Comment