如何将“根路径”捕获到变量中

时间:2018-05-22 09:30:19

标签: c# cmd process elevated-privileges

我正在尝试为logman.exe提升CMD,对于我尝试过的以下代码,

 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());
        }

它正在提供错误输出,如

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个问题,

  1. 当我运行应用程序exe时,它显示2 CMD窗口,第一个显示错误,第二个显示参数"cmd /k logman.exe PerfCounterCustom | findstr \"Root\"" [根路径]的结果
  2. 如何禁用显示两个窗口?

    1. 为什么我收到此错误?

3 个答案:

答案 0 :(得分:1)

至第一个问题:在ProcessStartInfoWindowStyleProcessWindowStyle.Hidden

答案 1 :(得分:1)

读取命令输出的另一种解决方案是将输出写入文本文件。因此,您必须在命令末尾添加>> "[Name or Path of file].txt"。然后只需从C#中读取文件,例如与File.ReadAllLines。 这里要考虑两件事: 如果您经常在运行时执行此操作,并且该命令会提供大量文本,请不要将其写入SSD。 请检查文件是否为空/之前不存在,因为Windows只是将输出附加到文件的末尾。如果在多个线程中运行,请在文件名中使用线程标识符。

答案 2 :(得分:0)

您必须将RedirectStandardOutput的{​​{1}}设置为ProcessStartInfo,并且必须在阅读输出之前运行true。 请注意,此解决方案导致与通过runas以管理员身份运行进程不兼容。