c#进程.开始:如何读取输出?



我尝试了其他问题的所有解决方案,但都不起作用。我也试过"调用filename.exe>log.txt";在CMD中,但它不起作用。如果你能帮我这个忙,我会很感激的。

我是一个不会说英语的学生,所以这个表达可能会很奇怪。我希望你能理解。

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()+"rn");
}
process.WaitForExit();
}

首先,在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;
}

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

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

最新更新