How to capture “Root Path” into a variable

2019-08-17 03:55发布

问题:

I am trying to run logman.exe for a elevated CMD, for this below code I tried,

 var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = @"C:\Windows\System32\cmd.exe",
                Arguments = "cmd /k logman.exe PerfCounterCustom  | findstr \"Root\"",
                Verb = "runas",
                UseShellExecute = true,
            }
        };

        try
        {
            proc.Start();
            while (!proc.StandardOutput.EndOfStream)
            {
                string line = proc.StandardOutput.ReadLine();
            }
            Console.WriteLine("Successfully elevated!");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

And it's giving error output like,

System.InvalidOperationException: StandardOut has not been redirected or the process hasn't started yet. at System.Diagnostics.Process.get_StandardOutput()

2 Questions,

  1. when I am running application exe, it's showing 2 CMD window, the 1st one showing error and 2nd one showing result for argument "cmd /k logman.exe PerfCounterCustom | findstr \"Root\"" [Root Path]

how to disable showing both window?

  1. Why I am getting this error?

回答1:

To your 1st Question: In the ProcessStartInfo set WindowStyle to ProcessWindowStyle.Hidden



回答2:

An alternative solution to read the output of the command is to write the output to a text file. Therefore you have to add >> "[Name or Path of file].txt" to the end of your command. Then just read the file from C# e.g. with File.ReadAllLines. Two things to consider here: If you do that often at Runtime and the command delivers huge amounts of text don't write it to an SSD. Please check that the file is empty / not existing before, because Windows just appends the output to the end of the file. If you run that in multiple threads use a thread identifier in the file name.



回答3:

You have to set RedirectStandardOutput of the ProcessStartInfo to true and you have to run proc.WaitForExit() before reading the output. Please note that this solution causes incompatibilities with running the process as administrator via runas.