process.standardoutput.ReadToEnd()总是空的?

我正在启动一个控制台应用程序,但是当我重定向标准输出时,我总是得不到任何东西!

当我不重定向它,并将CreateNoWindow设置为false ,我在控制台中正确地看到了所有内容,但是当我重定向它时, StandardOutput.ReadToEnd()始终返回一个空字符串。

  Process cproc = new Process(); cproc.StartInfo.CreateNoWindow = true; cproc.StartInfo.FileName = Dest; cproc.StartInfo.RedirectStandardOutput = true; cproc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; cproc.StartInfo.UseShellExecute = false; cproc.EnableRaisingEvents = true; cproc.Start(); cproc.Exited += new EventHandler(cproc_Exited); while(!stop) { result += cproc.StandardOutput.ReadToEnd(); } 

EventHandler cproc_exited只是将stop设置为true 。 有人可以解释为什么result总是string.Empty

你为什么要循环? 一旦它被读到最后,它将无法再读取任何数据,是吗?

您确定文本实际上是写入StandardOutput而不是StandardError吗?

(是的,显然你想将RedirectStandardOutput设置为true而不是false。我认为这只是你复制错误版本代码的情况。)

编辑:正如我在评论中所建议的那样,您应该从单独的线程中读取标准输出和标准错误。 不要等到进程退出 – 这可能会导致死锁,等待进程退出,但进程阻止尝试写入stderr / stdout,因为你没有从缓冲区中读取。

或者,您可以订阅OutputDataReceived和ErrorDataReceived事件,以避免使用额外的线程。

最好的方法是重定向输出并等待事件:

  // not sure if all this flags are needed process.StartInfo.CreateNoWindow = true; process.StartInfo.ErrorDialog = false; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.EnableRaisingEvents = true; process.OutputDataReceived += process_OutputDataReceived; process.ErrorDataReceived += process_ErrorDataReceived; process.Exited += process_Exited; process.Start(); void process_Exited(object sender, System.EventArgs e) { // do something when process terminates; } void process_OutputDataReceived(object sender, DataReceivedEventArgs e) { // a line is writen to the out stream. you can use it like: string s = e.Data; } void process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { // a line is writen to the out stream. you can use it like: string s = e.Data; } 

您已禁用标准输出的重定向。 尝试改变

 cproc.StartInfo.RedirectStandardOutput = false; 

 cproc.StartInfo.RedirectStandardOutput = true; 

以下来自MSDN的示例是否适合您?

 // Start the child process. Process p = new Process(); // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "Write500Lines.exe"; p.Start(); // Do not wait for the child process to exit before // reading to the end of its redirected stream. // p.WaitForExit(); // Read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); 

摆脱循环并将对ReadToEnd的调用ReadToEnd cproc_Exited