In the c # program, the cmd command is sometimes used to complete some functions. Therefore, the following method is found on the Internet to implement c # To execute the doscommand and return the result.
// DosCommand statement public string Execute (string dosCommand)
{Return Execute (dosCommand, timeout );}
/// <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 doscommand output </returns> public static string Execute (string command, int seconds)
{String output = ""; // output string if (dosCommand! = Null & dosCommand! = "")
{Process 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; // set parameters. "/C" indicates that the startInfo will be exited 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 ;}