process.standardoutput.ReadToEnd()总是空的?我正在启动一个控制台应用程序,但是当我重定向stdout时,我什么也没得到!当我不重定向它并将CreateNoWindow设置为false时,我会在控制台中正确地看到所有内容,但是当我重定向它时,StandardOutput.ReadToEnd()总是返回一个空字符串。进程cproc=newProcess();cproc.StartInfo.CreateNoWindow=true;cproc.StartInfo.FileName=目标;cproc.StartInfo.RedirectStandardOutput=true;cproc.StartInfo.WindowStyle=ProcessWindowStyle.Hidden;cproc.StartInfo.UseShellExecute=false;cproc.EnableRaisingEvents=true;cproc.开始();cproc.Exited+=newEventHandler(cproc_Exited);while(!stop){结果+=cproc.StandardOutput.ReadToEnd();}EventHandlercproc_exited只是将stop设置为true。有人可以解释为什么结果总是string.Empty吗?你为什么循环?一旦读取到最后,它就不能再读取任何数据了,是吗?您确定文本实际上是写入StandardOutput而不是StandardError吗?(是的,显然你想将RedirectStandardOutput设置为true而不是false。我认为这只是你复制了错误版本的代码的情况。)编辑:正如我在评论中建议的那样,你应该从一个单独的线程Standardoutput和标准错误。不要等到进程退出-这可能会导致死锁,等待进程退出但进程阻止尝试写入stderr/stdout,因为你没有从缓冲区读取。或者,您可以订阅OutputDataReceived和ErrorDataReceived事件以避免使用额外的线程。最好的方法是重定向输出并等待事件://不确定是否需要所有这些标志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;过程。开始();voidprocess_Exited(objectsender,System.EventArgse){//当进程终止时做一些事情;}voidprocess_OutputDataReceived(objectsender,DataReceivedEventArgse){//一行被写入输出流。你可以像这样使用它:strings=e.Data;}voidprocess_ErrorDataReceived(objectsender,DataReceivedEventArgse){//一行被写入输出流。你可以像这样使用它:strings=e.Data;}您已禁止使用标准输出的重定方向。尝试更改cproc.StartInfo.RedirectStandardOutput=false;进入cproc.StartInfo.RedirectStandardOutput=true;以下来自MSDN的示例是否适合您?//启动子进程。Processp=newProcess();//重定向子进程的输出流。p.StartInfo.UseShellExecute=false;p.StartInfo.RedirectStandardOutput=true;p.StartInfo.FileName="Write500Lines.exe";p.开始();//在读取到其重定向流的末尾之前,不要等待子进程退出。//p.WaitForExit();//先读取输出流再读取wait.stringoutput=p.StandardOutput.ReadToEnd();p.WaitForExit();跳出循环,调用ReadToEnd到ReadToEndcproc_Exited。以上就是C#学习教程:process.standardoutput.ReadToEnd()总是空的?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
