C # program calls cmd execution command (GO)

Source: Internet
Author: User

C # action to invoke the CMD command through a program

stringstr =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 windowstringOutput =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);

One thing to note is that after the previous command is completed, the Exit command is added, or the subsequent call to the ReadToEnd () command will suspend animation.

I did not add the Exit command at the time of the previous test, and after entering other commands, the window was suspended and there was no output.

For how to run as an administrator when executing the cmd command, you can read my previous article: C # How to run programs as an administrator-cool Kids-Blog Park

Another way C # calls the cmd command, but this method will "flash" the black window when it executes, and you can call it as you like when you use it.

/// <summary>///run the cmd command///The command window is displayed/// </summary>/// <param name= "CmdExe" >Specify the full path of the application</param>/// <param name= "Cmdstr" >executing command-line arguments</param>Static BOOLRuncmd (stringCmdExe,stringcmdstr) {    BOOLresult =false; Try    {        using(Process Mypro =NewProcess ()) {            //Specifies the application and command-line arguments that the startup process is callingProcessStartInfo psi =NewProcessStartInfo (CmdExe, CMDSTR); Mypro.startinfo=psi;            Mypro.start ();            Mypro.waitforexit (); Result=true; }    }    Catch    {    }    returnresult;}/// <summary>///run the cmd command///do not show command Window/// </summary>/// <param name= "CmdExe" >Specify the full path of the application</param>/// <param name= "Cmdstr" >executing command-line arguments</param>Static BOOLRUNCMD2 (stringCmdExe,stringcmdstr) {    BOOLresult =false; Try    {        using(Process Mypro =NewProcess ()) {MyPro.StartInfo.FileName="Cmd.exe"; MyPro.StartInfo.UseShellExecute=false; MyPro.StartInfo.RedirectStandardInput=true; MyPro.StartInfo.RedirectStandardOutput=true; MyPro.StartInfo.RedirectStandardError=true; MyPro.StartInfo.CreateNoWindow=true;            Mypro.start (); //If there are spaces in the calling program path, the cmd command fails to execute and can be enclosed in double quotes, where two quotation marks indicate a quotation mark (escape)            stringstr =string. Format (@"" " {0} "" {1} {2}", CmdExe, Cmdstr,"&exit");            MyPro.StandardInput.WriteLine (str); MyPro.StandardInput.AutoFlush=true;            Mypro.waitforexit (); Result=true; }    }    Catch    {    }    returnresult;}

C # program calls cmd execution command (GO)

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.