C # Run the CMD command and return the string

Source: Internet
Author: User
Public static void main (string [] ARGs)
{
// Console. writeline ("Hello world! ");
Console. writeline (execute ("netstat-n-B", 0 ));

Console. readkey (true );
}

Public static string execute (string doscommand, int outtime)
{
String output = "";
If (doscommand! = NULL & doscommand! = "")
{
Process = new process (); // create a process object
Processstartinfo startinfo = new processstartinfo (); // a set of values used when creating a process, as shown in the following attributes:
Startinfo. filename = "cmd.exe"; // set the command program to be executed
// The method for hiding the CMD window is as follows:
Startinfo. Arguments = "/C" + doscommand; // set the parameter. To enter the characters in the command program, "/C" indicates that the command exits immediately after execution.
Startinfo. useshellexecute = false; // do not start with the system shell program
Startinfo. redirectstandardinput = false; // The input is not redirected.
Startinfo. redirectstandardoutput = true; // The redirected output is not displayed on the DOS console by default.
Startinfo. createnowindow = true; // do not create a window
Process. startinfo = startinfo;

Try
{
If (process. Start () // start the process
{
If (outtime = 0)
{Process. waitforexit ();}
Else
{Process. waitforexit (outtime );}
Output = process. standardoutput. readtoend (); // read the output of the process.
}
}
Catch
{

}
Finally
{
If (process! = NULL)
{Process. Close ();}
}
}
Return output;
}

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.