Keep console window of a new Process open after it finishes

前端 未结 4 1794
一向
一向 2020-12-01 10:15

I currently have a portion of code that creates a new Process and executes it from the shell.

Process p = new Process();
...
p.Start();
p.WaitForExit();
         


        
4条回答
  •  情深已故
    2020-12-01 10:51

    It is easier to just capture the output from both the StandardOutput and the StandardError, store each output in a StringBuilder and use that result when the process is finished.

    var sb = new StringBuilder();
    
    Process p = new Process();
    
    // redirect the output
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    
    // hookup the eventhandlers to capture the data that is received
    p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
    p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);
    
    // direct start
    p.StartInfo.UseShellExecute=false;
    
    p.Start();
    // start our event pumps
    p.BeginOutputReadLine();
    p.BeginErrorReadLine();
    
    // until we are done
    p.WaitForExit();
    
    // do whatever you need with the content of sb.ToString();
    

    You can add extra formatting in the sb.AppendLine statement to distinguish between standard and error output, like so: sb.AppendLine("ERR: {0}", args.Data);

提交回复
热议问题