C # execute the doscommand

Source: Internet
Author: User

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 ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.