antonio
antonio

Reputation: 11120

C#: run command with elevated permissions and capture output

I'd like to run a command with elevated permissions while capturing the output:

using System.Diagnostics;
namespace SO
{
    class Program
    {
        static void Main(string[] args)
        {

            ProcessStartInfo startInfo  = new ProcessStartInfo("FSUTIL", "dirty query c:");
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.Verb = "runas";

            var proc = new Process();
            proc.StartInfo = startInfo;
            proc.Start();
            proc.WaitForExit();
            string output = proc.StandardOutput.ReadToEnd();
            System.Console.WriteLine(output);
        }
    }
}

The problem is that startInfo.Verb = "runas"; requires startInfo.UseShellExecute = true;, which is not compatible RedirectStandardOutpu.

Any possible solutions?

Upvotes: 1

Views: 495

Answers (1)

Gusman
Gusman

Reputation: 15151

This is not an exact answer to your request, but will show you some problems on your approach and a way to avoid all.

If your program doesn't runs as elevated, each time you call the external program it will request elevated privileges to the user, so at some point the user will be requested to elevate privileges to a program.

Said so, you can run your program with elevated privileges, in this way when you launch the external program it will inherit the elevated privileges.

To do your program to request elevated privileges on run read this post.

Upvotes: 0

Related Questions