This article implements the ability of C # to run the CMD command implicitly. is the main screen of the instance program. Enter the DOS command in the command text box and click the "Run" button to output the result in the text box below.
The following is the complete code for the program. This program does not use the p.standardoutput.readtoend () and P.standardoutput.readline () methods to obtain the output, because these methods are executed after the screen is easy to die. Instead, you get the output by calling the Async method beginoutputreadline , and the event p. outputdatareceived Handle The results in the event handling method.
Using system;using system.diagnostics;using system.io;using System.Windows.Forms; Namespace rundoscommandform{publicpartialclassform1:form {PublicForm1 () {Initializecomp Onent (); } Privatevoidbutton1_click (object sender, Eventargse) {Excutedoscommand (TextBox1.Text); } privatevoidexcutedoscommand (string cmd) {try {Process p = newproces S (); p.StartInfo.FileName = "cmd"; P.startinfo.useshellexecute = false; P.startinfo.redirectstandardinput = true; P.startinfo.redirectstandardoutput = true; P.startinfo.redirectstandarderror = true; P.startinfo.createnowindow = true; P.outputdatareceived + = Newdatareceivedeventhandler (sortprocess_outputdatareceived); P.start (); StreamWriter cmdwriter = p.standardinput; P.beginoutputreadline (); if (! String.IsNullOrEmpty (cmd)) {cmdwriter.writeline (cmd); } cmdwriter.close (); p.WaitForExit (); P.close (); } catch (Exception ex) {MessageBox.Show ("failed to execute command, please check that the command entered is correct!") "); }} privatevoidsortprocess_outputdatareceived (Object Sender,datareceivedeventargs e) {if (! String.IsNullOrEmpty (E.data)) {this. BeginInvoke (Newaction (() = {THIS.LISTBOX1.ITEMS.ADD (e.data);})); } } }}
We can also save the cmd command that needs to be run as a bat file, and then use the process class to execute.
C # implicit shipping cmd command