C# Process.Start: 如何读取输出?

C# Process.Start: how to read output?

我尝试了其他问题的所有解决方案,但其中 none 行得通。我也试过在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();
                }

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

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

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

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

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