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
。
上述就是C#学习教程:process.standardoutput.ReadToEnd()总是空的?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1019824.html