in C # Program , the CMD command is sometimes used to complete some functions. Therefore, the following method is found on the Internet, implemented
C # To execute the doscommand and return the result.
// Doscommand statement Public String execute (string doscommand) {return execute (doscommand, 10) ;}/// <summary> /// execute the doscommand, return doscommand output /// </Summary> /// <Param name = "doscommand"> doscommand </param> /// <Param name = "milliseconds"> wait for the command execution time (unit: millisecond), // if it is set to 0, it will be infinitely waiting </param> /// <returns> to return the output of the doscommand </returns> Public static string execute (string command, int seconds) {string output = ""; // output string if (command! = NULL &&! Command. equals ("") {Process = new process (); // create the process object processstartinfo startinfo = new processstartinfo (); startinfo. filename = "cmd.exe"; // set the command startinfo to be executed. arguments = "/C" + command; // "/C" indicates to exit startinfo immediately after the command is executed. useshellexecute = false; // do not use the System Shell to start startinfo. redirectstandardinput = false; // do not redirect the input startinfo. redirectstandardoutput = true; // redirect the output startinfo. createnowindow = true; // do not create a window Process. startinfo = startinfo; try {If (process. start () // start process {If (seconds = 0) {process. waitforexit (); // here the infinite waiting process ends} else {process. waitforexit (seconds); // wait for the process to end. The waiting time is specified in milliseconds.} output = process. standardoutput. readtoend (); // read process output} catch {} finally {If (process! = NULL) process. Close () ;}return output ;}