0

我使用以下代码捕获 cmd 文件的输出:

com = "Parameter";
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = Properties.Settings.Default.pathTo + @"copy.cmd";
startInfo.Arguments = com;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.WriteLine(process.StandardError.ReadToEnd());

没关系,但是我在 cmd 完成后得到输出。cmd运行时如何获得输出?

4

1 回答 1

1

由于这个调用,你最终得到了输出:

process.WaitForExit();

这会阻止您的代码执行,直到命令完成。

要在输出时读取输出,请不要将WaitForExit()调用放在那里并从 StandardOutput数据到达时读取,例如:

while ((var str = process.StandardOutput.ReadLine()) != null)
{
    // do something with str
}
于 2013-04-11T21:41:56.163 回答