How to capture “Root Path” into a variable

2019-08-17 04:04发布

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,

enter image description here

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?

3条回答
Luminary・发光体
2楼-- · 2019-08-17 04:24

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.

查看更多
时光不老,我们不散
3楼-- · 2019-08-17 04:25

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.

查看更多
唯我独甜
4楼-- · 2019-08-17 04:34

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

查看更多
登录 后发表回答