In many cases, we need to obtain the output content of the command line through programming. After studying it for a lot of time, we finally got it done.
There are two methods to obtain the output content of the command line: traditional and asynchronous.
Traditional methods:
1 Using (Process = New System. Diagnostics. Process ())
2 {
3 Process. startinfo. filename = " Ping " ;
4 Process. startinfo. Arguments = " Www.ymind.net " ;
5 // OS shell must be disabledProgram
6 Process. startinfo. useshellexecute = False ;
7 Process. startinfo. createnowindow = True ;
8 Process. startinfo. redirectstandardoutput = True ;
9
10 Process. Start ();
11
12 String Output = process. standardoutput. readtoend ();
13
14 If (String. isnullorempty (output) = False )
15 This . Textbox1.appendtext (output +" \ R \ n " );
16
17 Process. waitforexit ();
18 Process. Close ();
19 }
Asynchronous mode:
1 Private Void Button3_click ( Object Sender, eventargs E)
2 {
3 Using (Process = New System. Diagnostics. Process ())
4 {
5 Process. startinfo. filename = " Ping " ;
6 Process. startinfo. Arguments = " Www.ymind.net-T " ;
7 // OS shell must be disabled
8 Process. startinfo. useshellexecute = False ;
9 Process. startinfo. createnowindow = True ;
10 Process. startinfo. redirectstandardoutput = True ;
11
12 Process. Start ();
13
14 // Asynchronously obtain command line Content
15 Process. beginoutputreadline ();
16
17 // Obtain subscription events Asynchronously
18 Process. outputdatareceived + = New Datareceivedeventhandler (process_outputdatareceived );
19 }
20 }
21
22 Private Void Process_outputdatareceived ( Object Sender, datareceivedeventargs E)
23 {
24 // Here is only an example of output. In fact, you can cancel obtaining the command line content as needed.
25 // Reference: process. canceloutputread ()
26
27 If (String. isnullorempty (E. Data) = False )
28 This . Appendtext (E. Data + " \ R \ n " );
29 }
30
31 # Region Solve the problem of control access under multiple threads
32
33 Public Delegate Void Appendtextcallback ( String Text );
34
35 Public Void Appendtext ( String Text)
36 {
37 If ( This . Textbox1.invokerequired)
38 {
39 Appendtextcallback d = New Appendtextcallback (appendtext );
40 This . Textbox1.invoke (D, text );
41 }
42 Else
43 {
44 This . Textbox1.appendtext (text );
45 }
46 }
47
48 # Endregion