【问题标题】:how to capture output for Process into a C# variable? [duplicate]如何将 Process 的输出捕获到 C# 变量中? [复制]
【发布时间】:2024-10-26 05:00:02
【问题描述】:

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

C:\>logman.exe FabricTraces | findstr Root
Root Path: C:\ProgramData\Windows Fabric\Fabric\log\Traces\

现在,我正在尝试在 C# 程序中模仿相同的内容,并希望将输出 (C:\ProgramData\Windows Fabric\Fabric\log\Traces\) 捕获到一个变量中。

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

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

【问题讨论】:

  • this 有帮助吗?
  • 非常感谢斯蒂芬....
  • 如果您想使用管道和其他 shell 功能,您必须使用 /C 选项启动 cmdFabricTraces | findstr Root 不是进程的参数字符串...

标签: c# cmd system.diagnostics


【解决方案1】:

类似这样的:

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 */
}

【讨论】: