只要您使用.net4.5/c#5,接受的答案就会建议采用不同的方法。我的程序正在调用gdalwarp.exe以对大型tiff文件执行长时间运行的过程。Galwarp.exe以这种格式输出。创建6014Px4988L的输出文件。处理输入文件[FileName].tiff。使用源图像的波段4作为alpha。使用目标图像的波段4作为alpha。0...10...20...30。..40...50...60...70...80...90...100-完成。最后一行缓慢流入以指示进度。我想在每次更改时阅读该行,以便我可以移动进度条并让用户了解情况。首先,我尝试阅读Process.StandardOutput,但在整个过程完成之前它不会提供任何数据。其次,我尝试调用Process.BeginOutputReadLine()并连接事件Process.OutputDataReceived但它仅在一行完成时触发。这是对执行GDalWarp.exe的调用。publicstaticvoidResizeTiff(stringSourceFile,stringDestinationFile,floatResolutionWidth,floatResolutionHeight,GuidProcessId){vardirectory=GDalBin;varexe=Path.Combine(目录,“gdalwarp.exe”);varargs="-ts"+ResolutionWidth+""+ResolutionHeight+"-rcubic-co"TFW=YES"""+SourceFile+""""+DestinationFile+""";ExecuteProcess(exe,args,null,directory,0,null,true,true,0);这是我在静态函数中的工作代码,它只在进程退出后读取输出。publicstaticstringExecuteProcess(stringFilePath,stringArgs,stringInput,stringWorkingDir,intWaitTime=0,DictionaryEnviroVariables=null,boolTrace=false,boolThrowError=true,intValidExitCode=0){varprocessInfo="FilePath:"+FilePath+"n"+(WaitTime>0?"WaitTime:"+WaitTime.ToString()+"msn":"")+(!string.IsNullOrEmpty(Args)?"Args:"+Args+"n":"")+(!string.IsNullOrEmpty(Input)?"Input:"+Input+"n":"")+(!string.IsNullOrEmpty(WorkingDir)?"WorkingDir:"+WorkingDir+"n":"")+(EnviroVariables!=null&&EnviroVariables.Count>0?"环境变量:"+string.Join(",",EnviroVariables.Select(a=>a.Key+"="+a.Value))+“n”:“”);if(Trace)Log.Debug("正在使用以下参数运行外部进程:n"+processInfo);varstartInfo=(string.IsNullOrEmpty(Args))?新的ProcessStartInfo(文件路径):新的ProcessStartInfo(文件路径,参数);如果(!string.IsNullOrEmpty(WorkingDir))startInfo.WorkingDirectory=WorkingDir;startInfo.UseShellExecute=false;startInfo.RedirectStandardOutput=true;startInfo.RedirectStandardError=true;startInfo.CreateNoWindow=true;如果(!string.IsNullOrEmpty(Input))startInfo.RedirectStandardInput=true;if(EnviroVariables!=null)foreach(KeyValuePairentryinEnviroVariables)startInfo.EnvironmentVariables.Add(entry.Key,entry.Value);varprocess=newProcess();process.StartInfo=startInfo;如果(process.Start()){如果(输入!=null&&输入!=“”){process.StandardInput.Write(输入);process.StandardInput.Close();}varstandardError="";varstandardOutput="";int退出代码=0;varerrorReadThread=newThread(newThreadStart(()=>{standardError=process.StandardError.ReadToEnd();}));varoutputReadTread=newThread(newThreadStart(()=>{standardOutput=process.StandardOutput.ReadToEnd();}));errorReadThread.Start();输出ReadTread。开始();varsw=Stopwatch.StartNew();布尔超时=假;尝试{while(errorReadThread.IsAlive||outputReadTread.IsAlive){Thread.Sleep(50);如果(WaitTime>0&&sw.ElapsedMilliseconds>WaitTime){如果(errorReadThread.IsAlive)errorReadThread.Abort();如果(outputReadTread.IsAlive)outputReadTread.Abort();超时=真;休息;}}如果(!process.HasExited)process.Kill();if(timedOut)thrownewTimeoutException("执行外部进程时超时。n"+processInfo+"标准输出:"+standardOutput+"n标准错误:"+standardError);exitCode=process.ExitCode;}最后{sw.Stop();过程。关闭();处理.处置();}if(ThrowError&&exitCode!=ValidExitCode)thrownewException("执行外部进程返回错误。n"+processInfo+"退出代码:"+exitCode+"nStandard输出:"+standardOutput+"nStandard错误:“+标准错误);如果(跟踪)Log.Debug("ProcessExitedwiththefollowingvalues:nExitCode:{0}nStandardOutput:{1}nStandardError:{2}",exitCode,standardOutput,standardError);返回标准输出;}否则返回空值;谁能帮我实时阅读这个输出?这是你的问题的解决方案,但它有点棘手,因为gdalwarp.exe阻塞了标准输出,你可以将它的输出重定向到一个文件并读取它的变化你可以使用FileSystemWatcher来检测文件中的变化,但有时它不够可靠.如果OutputCallback不为??null,则在outputReadThread中使用以下简单的轮询方法来获取文件大小的变化。这是对ExecuteProcess的调用,带有回调以立即接收流程输出。publicstaticvoidResizeTiff(stringSourceFile,stringDestinationFile,floatResolutionWidth,floatResolutionHeight,GuidProcessId){vardirectory=GDalBin;varexe=Path.Combine(目录,“gdalwarp.exe”);varargs="-ts"+ResolutionWidth+""+ResolutionHeight+"-rcubic-co"TFW=YES"""+SourceFile+""""+DestinationFile+""";浮动进度=0;Actioncallback=delegate(stringfullOutput,stringnewOutput){浮点值;如果(float.TryParse(newOutput,outvalue))progress=value;elseif(newOutput==".")进度+=2.5f;否则如果(newOutput.StartsWith("100"))进度=100;};ExecuteProcess(exe,args,null,directory,0,null,true,true,0,callback);这是一个调用任何进程并在它发生时接收结果的函数。以上就是C#学习教程:接收新行前阅读ProcessStandardOutput分享的所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多加关注—publicstaticstringExecuteProcess(stringFilePath,stringArgs,stringInput,stringWorkingDir,intWaitTime=0,DictionaryEnviroVariables=null,boolTrace=false,boolThrowError=true,intValidExitCode=0,ActionOutputChangedCallback=null){varprocessInfo="FilePath:"+FilePath+"n"+(WaitTime>0?"WaitTime:"+WaitTime.ToString()+"msn":"")+(!string.IsNullOrEmpty(Args)?"Args:"+Args+"n":"")+(!string.IsNullOrEmpty(Input)?"输入:"+输入+"n":"")+(!string.IsNullOrEmpty(WorkingDir)?"WorkingDir:"+WorkingDir+"n":"")+(EnviroVariables!=null&&EnviroVariables.Count>0?"环境变量:"+string.Join(",",EnviroVariables.Select(a=>a.Key+"="+a.Value))+"n":"");字符串输出文件="";如果(OutputChangedCallback!=null){outputFile=Path.GetTempFileName();参数="/C"""+文件路径+"""+Args+"">"+输出文件;文件路径="cmd.exe";}varstartInfo=(string.IsNullOrEmpty(Args))?新的ProcessStartInfo(文件路径):新的ProcessStartInfo(文件路径,参数);如果(!string.IsNullOrEmpty(WorkingDir))startInfo.WorkingDirectory=WorkingDir;startInfo.UseShellExecute=false;startInfo.CreateNoWindow=true;如果(OutputChangedCallback==null){startInfo.RedirectStandardOutput=true;startInfo.RedirectStandardError=true;}else{startInfo.RedirectStandardOutput=false;startInfo.RedirectStandardError=false;}如果(!string.IsNullOrEmpty(Input))startInfo.RedirectStandardInput=true;if(EnviroVariables!=null)foreach(KeyValuePairentryinEnviroVariables)startInfo.EnvironmentVariables.Add(entry.Key,entry.Value);varprocess=newProcess();process.StartInfo=startInfo;if(process.Start()){if(Trace)Log.Debug("正在使用以下参数运行外部进程:n"+processInfo);尝试{如果(!string.IsNullOrEmpty(Input)){process.StandardInput.Write(Input);process.StandardInput.Close();}varstandardError="";varstandardOutput="";int退出代码=0;线程错误ReadThread;线程输出ReadThread;如果(OutputChangedCallback==null){errorReadThread=newThread(newThreadStart(()=>{standardError=process.StandardError.ReadToEnd();}));outputReadThread=newThread(newThreadStart(()=>{standardOutput=process.StandardOutput.ReadToEnd();}));}else{errorReadThread=newThread(newThreadStart(()=>{}));outputReadThread=newThread(newThreadStart(()=>{longlen=0;while(!process.HasExited){if(File.Exists(outputFile)){varinfo=newFileInfo(outputFile);if(info.Length!=len){varcontent=newStreamReader(File.Open(outputFile,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)).ReadToEnd();varnewContent=content.Substring((int)len,(int)(info.Length-len));len=info.Length;OutputChangedCallback.Invoke(内容,新内容);}}Thread.Sleep(10);}}));}errorReadThread.Start();outputReadThread.Start();varsw=Stopwatch.StartNew();布尔超时=假;尝试{while(errorReadThread.IsAlive||outputReadThread.IsAlive){Thread.Sleep(50);如果(WaitTime>0&&sw.ElapsedMilliseconds>WaitTime){如果(errorReadThread.IsAlive)errorReadThread.Abort();如果(outputReadThread.IsAlive)outputReadThread.Abort();超时=真;休息;}}如果(!process.HasExited)process.Kill();if(timedOut)thrownewTimeoutException("执行外部进程时超时。n"+processInfo+"标准输出:"+standardOutput+"n标准错误:"+standardError);exitCode=process.ExitCode;}最后{sw.Stop();过程。关闭();处理.处置();}if(ThrowError&&exitCode!=ValidExitCode)thrownewException("执行外部进程返回错误。n"+processInfo+"退出代码:"+exitCode+"nStandard输出:"+standardOutput+"nStandardError:"+standardError);if(Trace)Log.Debug("ProcessExitedwiththefollowingvalues:nExitCode:{0}nStandardOutput:{1}nStandardError:{2}",exitCode,standardOutput,standardError);returnstandardOutput;}finally{FileUtilities.AttemptToDeleteFiles(newstring[]{outputFile});}}elsethrownewException("Theprocessfailedtostart.n"+processInfo);它是收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除,如需转载请注明出处:
