如何捕获“根路径”?变成一个变量 [英] How to capture "Root Path" into a variable

查看:58
本文介绍了如何捕获“根路径”?变成一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为升高的 CMD 运行 logman.exe ,为此我尝试了以下代码,

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尚未重定向或程序尚未开始。
,位于System.Diagnostics.Process.get_StandardOutput()

2个问题,


  1. 当我运行应用程序 exe 时,它显示2个 CMD 窗口,参数 cmd / k logman.exe PerfCounterCustom | findstr \ Root\ [Root Path]
  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. 为什么会出现此错误?


推荐答案

阅读命令的输出是将输出写入文本文件。因此,您必须添加>> [[文件名或路径] .txt 到命令末尾。然后只需从C#中读取文件即可使用 File.ReadAllLines
这里要考虑两件事:
如果您经常在运行时执行此操作,并且该命令传递了大量文本,请不要将其写入SSD。
请检查文件是否为空/之前不存在,因为Windows只是将输出附加到文件末尾。如果在多个线程中运行,请在文件名中使用线程标识符。

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.

这篇关于如何捕获“根路径”?变成一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆