如何将进程的输出捕获到 C# 变量中



>我在 windows 命令提示符下运行以下命令,它给出的输出如下所示,

C:>logman.exe FabricTraces | findstr Root
Root Path: C:ProgramDataWindows FabricFabriclogTraces

现在,我正在尝试在C#程序中模仿相同的内容,并希望将输出(C:ProgramDataWindows FabricFabriclogTraces(捕获到变量中。

如何做到这一点,这是我尝试过的代码,

Process P = Process.Start("logman.exe", "FabricTraces | findstr Root");
            P.WaitForExit();
            var result = P.ExitCode;

像这样:

private void StartProcess()
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    process.StartInfo.FileName               = /* path + binary */;
    process.StartInfo.Arguments              = /* arguments */;
    process.StartInfo.WorkingDirectory       = /* working directory */;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError  = true;
    process.StartInfo.UseShellExecute        = false;
    process.StartInfo.CreateNoWindow         = true;
    process.OutputDataReceived += Process_OutputDataReceived;
    process.ErrorDataReceived += Process_ErrorDataReceived;
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}
private void Process_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
    /* e.Data will contain string with error message */
}
private void Process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
    /* e.Data will contain string with output */
}

相关内容

  • 没有找到相关文章

最新更新