/// <summary> ///Execute cmd command/// </summary> /// <param name= "str" ></param> /// <returns></returns> Public Static stringExecmd (stringstr) { Try { //string str = Console.ReadLine ();System.Diagnostics.Process p =NewSystem.Diagnostics.Process (); p.StartInfo.FileName="Cmd.exe"; P.startinfo.useshellexecute=false;//whether to start with the operating system shellP.startinfo.redirectstandardinput =true;//accept input from the calling programP.startinfo.redirectstandardoutput =true;//get output information from the calling programP.startinfo.redirectstandarderror =true;//REDIRECT standard error OutputP.startinfo.createnowindow =true;//do not show program windowP.start ();//Start the program//send input information to the CMD windowP.standardinput.writeline (str +"&exit"); P.standardinput.autoflush=true; //P.standardinput.writeline ("exit"); //writes the command to be executed to the standard input. The use of & here is a symbol of the batch command, indicating that the previous command executes the following (exit) command regardless of whether the execution succeeds, and if the exit command is not executed, the subsequent call to the ReadToEnd () method will feign death.//Similar symbols are also available in && | | The former indicates that the previous command must be successful before the subsequent command is executed, which means that the previous command execution must fail before the subsequent command is executed//gets the output information of the cmd window stringOutput =P.standardoutput.readtoend (); //StreamReader reader = p.standardoutput; //string Line=reader. ReadLine (); //While (!reader. Endofstream)//{ //str + = line + ""; //Line = reader. ReadLine (); //}p.waitforexit ();//wait for the program to finish executing the exit processP.close (); Console.WriteLine (output); returnoutput; } Catch(Exception ex) {return NULL; } }
C # Methods for executing CMD commands