Asp. NET Execute cmd command

Source: Internet
Author: User
Tags sin

Batch command is the fastest and most efficient command to execute. Because the batch command, plainly speaking, is the MS-DOS environment command, there are a lot of batch commands, are pure DOS commands.

However, although the batch command is powerful, there are shortcomings. Batch commands can only perform basic functions and cannot complete complex network functions. Therefore, in many cases, program developers often use a variety of development languages as development tools, with batch processing commands, to achieve powerful execution of faster projects.

Below, this station to you to introduce is, how in CS structure of C # program , call MS-DOS window , run multiple batch command .

  I. Introduction of namespaces

First, in the CS file header, refer to the following code:

Using System.Diagnostics;

  Second, the function code

public void Mybatcommand ()//Name
{
Three strings below, representing three batch commands
String MyDosComLine1, MyDosComLine2, MyDosComLine3;

MyDosComLine1 = "cd\";//returns the root directory command
MyDosComLine2 = "CD MyFiles";//Enter the MyFiles directory
MyDosComLine3 = "Copy * * * e:\";//copy and paste all files from the current directory to E Drive

Process myprocess = new process ();
MyProcess.StartInfo.FileName = "cmd.exe";//Open DOS control platform
MyProcess.StartInfo.UseShellExecute = false;
MyProcess.StartInfo.CreateNoWindow = true;//Whether the DOS window is displayed, true is hidden;
MyProcess.StartInfo.RedirectStandardInput = true;
MyProcess.StartInfo.RedirectStandardOutput = true;
MyProcess.StartInfo.RedirectStandardError = true;
Myprocess.start ();
StreamWriter sIn = myprocess.standardinput;//Standard input stream
Sin.autoflush = true;
StreamReader sOut = myprocess.standardoutput;//Standard input stream
StreamReader SERR = myprocess.standarderror;//standard error stream

Sin.write (MyDosComLine1 System.Environment.NewLine);//First DOS command
Sin.write (MyDosComLine2 System.Environment.NewLine);//Second DOS command
Sin.write (MyDosComLine3 System.Environment.NewLine);//Third DOS command
Sin.write ("Exit" System.Environment.NewLine);//Fourth DOS command, Exit DOS window

string s = Sout.readtoend ();//Read output information after executing DOS command
String er = Serr.readtoend ();//Read error message after executing DOS command
if (myprocess.hasexited = = False)
{
Myprocess.kill ();
MessageBox.Show (ER);
}
Else
{
MessageBox.Show (s);
}

Sin.close ();
Sout.close ();
Serr.close ();
Myprocess.close ();
}

Part of the code explains:

To run multiple batch commands in C #, we can use the following format to add multiple commands.

  Sin.write (DOS command code System.Environment.NewLine);

  Where the DOS command code is what you want to do with the batch command, and System.Environment.NewLine indicates that the line wraps after the batch command.

For example:

publicvoidExecuteCmd(string cmd){            Process p = newProcess();            p.StartInfo.FileName = "cmd.exe";            p.StartInfo.UseShellExecute = false;            p.StartInfo.RedirectStandardInput = true;            p.StartInfo.RedirectStandardOutput = true;            p.StartInfo.RedirectStandardError = true;            p.StartInfo.CreateNoWindow = true;            p.Start();            //设置自动刷新缓冲并更新            p.StandardInput.AutoFlush = true;            //写入命令            p.StandardInput.WriteLine(cmd);            p.StandardInput.WriteLine("exit");            //等待结束            p.WaitForExit();            p.Close(); }

For example:
  1. Doscommand DOS command statement statement One && statement two statements one execution success before executing two
  2. Public string Execute (string doscommand)
  3. {
  4. return Execute (Doscommand, 10);
  5. }
  6. <summary>
  7. Executes a DOS command that returns the output of a DOS command
  8. </summary>
  9. <param name= "doscommand" >dos command </param>
  10. <param name= "milliseconds" > Wait Time for command execution (in milliseconds),
  11. If set to 0, infinite wait </param>
  12. <returns> returns the output of the DOS command </returns>
  13. Public static string Execute (string command, int seconds)
  14. {
  15. string output = ""; //output string
  16. if (command ! = null &&!command. Equals (""))
  17. {
  18. Process Process = new process (); Create a Process object
  19. ProcessStartInfo startinfo = new ProcessStartInfo ();
  20. Startinfo.filename = "cmd.exe"; Set the command to be executed
  21. Startinfo.arguments = "/C" + command; "/C" means to exit immediately after executing the command.
  22. Startinfo.useshellexecute = false; Booting without using the system shell
  23. Startinfo.redirectstandardinput = false; Do not redirect input
  24. Startinfo.redirectstandardoutput = true; //redirect Output
  25. Startinfo.createnowindow = true; Do not create a window
  26. Process. StartInfo = StartInfo;
  27. Try
  28. {
  29. if (process. Start ())//Begin process
  30. {
  31. if (seconds = = 0)
  32. {
  33. Process. WaitForExit (); //Here Infinite wait process end
  34. }
  35. Else
  36. {
  37. Process. WaitForExit (seconds); //wait for the process to end, waiting time for the specified millisecond
  38. }
  39. Output = process. Standardoutput.readtoend (); //Read the output of the process
  40. }
  41. }
  42. Catch
  43. {
  44. }
  45. finally
  46. {
  47. if (process! = null)
  48. Process. Close ();
  49. }
  50. }
  51. return output;
  52. }
  53. Using System;

    Using System.Collections;

    Using System.Configuration;

    Using System.Data;

    Using System.Linq;

    Using System.Web;

    Using System.Web.Security;

    Using System.Web.UI;

    Using System.Web.UI.HtmlControls;

    Using System.Web.UI.WebControls;

    Using System.Web.UI.WebControls.WebParts;

    Using System.Xml.Linq;

    Using System.Diagnostics;

    Namespace WebForm

    {

    public partial class _default:system.web.ui.page

    {

    protected void Page_Load (object sender, EventArgs e)

    {

    Response.Write (Execommand ("ping www.126.com"));

    }

    public string Execommand (string commandtext)

    {

    Process P = new process ();

    p.StartInfo.FileName = "cmd.exe";

    P.startinfo.useshellexecute = false;

    P.startinfo.redirectstandardinput = true;

    P.startinfo.redirectstandardoutput = true;

    P.startinfo.redirectstandarderror = true;

    P.startinfo.createnowindow = true;

    string stroutput = null;

    Try

    {

    P.start ();

    P.standardinput.writeline (CommandText);

    P.standardinput.writeline ("Exit");

    Stroutput = P.standardoutput.readtoend ();

    p.WaitForExit ();

    P.close ();

    }

    catch (Exception e)

    {

    Stroutput = E.message;

    }

    return stroutput;

    }

    }

    }

Asp. NET Execute cmd command

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.