Using events and delegates, the process has 2 events outputdatareceived, errordatareceived can be used to redirect standard output and standard error output;
It is important to note that inputdatareceived is not a process event, so standard input cannot be so redirected;
Need to add before use: Using System.Diagnostics; can use process
Step one: Identify essential ingredients
1 Process startinfostartinfo =newprocessstartinfo (. exe); 2 true; // do not create a window 3 false ; 4 // do not use system shell to start, redirect output must be set to False 5 true // REDIRECT output, 6 true;
Step two: Using the try Catch block
1 Try2 {3Processprocess =Process.Start (startinfo);4Process. Outputdatareceived + = (s, _e) =Console.WriteLine (_e.data);5Process. Errordatareceived + = (s, _e) =Console.WriteLine (_e.data);6 //when EnableRaisingEvents is true, process exits with the following delegate function called7Process. Exited + = (s, _e) = Console.WriteLine ("Exited with"+_process. ExitCode);8Process. EnableRaisingEvents =true;9 process. Beginoutputreadline ();Ten process. Beginerrorreadline (); One process. WaitForExit (); A } - Catch(Exception e) - { the Console.WriteLine (ex. Message); -}
It is important to note that asynchronous and synchronous read operations cannot be mixed with the same redirect stream.
After you open the redirect stream for a Process in asynchronous or synchronous mode, all further read operations on the stream must be in the same mode.
For example, do not call Beginoutputreadline after the standardoutput stream and then call ReadLine, and vice versa.
However, you can read two different streams in different modes. For example, you can call beginoutputreadlineFirst, and then call ReadLinefor the standarderror stream.
C # Input and output redirection method two: asynchronous process