C# 运行时获取cmd的输出

C# 运行时获取cmd的输出,c#,cmd,C#,Cmd,我用以下代码捕获cmd文件的输出: com = "Parameter"; System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = Properties.Settings.Default.pa

我用以下代码捕获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运行时,如何获取输出?

由于此调用,您最终将获得输出:

process.WaitForExit();
它会阻止代码执行,直到命令完成

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

while ((var str = process.StandardOutput.ReadLine()) != null)
{
    // do something with str
}

我有一种奇怪的担心,如果有太多的输出到stderr,那么copy.cmd可能会被阻塞,因为它无法再写入stderr(流控制)。我不知道是否有某种机制可以防止这个问题。