【问题标题】:C# Process.Start: how to read output?C# Process.Start:如何读取输出?
【发布时间】:2021-08-13 06:14:02
【问题描述】:

我尝试了其他问题的所有解决方案,但都没有奏效。我还尝试在 CMD 中“调用 filename.exe>log.txt”,但没有成功。如果您能帮我解决这个问题,我将不胜感激。

我是一个非英语的学生,所以表达可能会很奇怪。感谢您的理解。

using (Process process = new Process())
                {
                    process.StartInfo.FileName = ProcessPath;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardInput = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.WorkingDirectory = Path.GetDirectoryName(ProcessPath);
                    process.Start();

                    while (process.HasExited)
                    {
                        TextBox1.AppendText(process.StandardOutput.ReadLine()+"\r\n");
                    }

                    process.WaitForExit();
                }

【问题讨论】:

标签: c# process output


【解决方案1】:

首先,您在 while 循环中检查 process.HasExited。 这当然默认为 false,然后您的代码将跳过它。这就是为什么我建议使用异步方法或基于事件的方法。

如果你选择异步,你可以这样做:

using (var process = Process.Start(psi))
{
    errors = await process.StandardError.ReadToEndAsync();
    results = await process.StandardOutput.ReadToEndAsync();
}

这里,psiProcessStartInfo 的一个实例。
您可以在创建流程后设置它们,但您可以创建一个对象并将其传递给构造函数。

如果你不能让它异步,你可以这样做:

using (var process = Process.Start(psi))
{
    errors = process.StandardError.ReadToEndAsync().Result;
    results = process.StandardOutput.ReadToEndAsync().Result;
}

【讨论】:

  • 谢谢你!我试试这个方法!
【解决方案2】:

使用事件并在开始前设置它们:

process.ErrorDataReceived += (sendingProcess, errorLine) => error.AppendLine(errorLine.Data);
process.OutputDataReceived += (sendingProcess, dataLine) => SetLog(dataLine.Data);

【讨论】:

  • 谢谢!我试试看!
猜你喜欢
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2014-08-04
  • 2016-08-13
  • 1970-01-01
相关资源
最近更新 更多