C # How to call the execution of the CMD Program

Source: Internet
Author: User

The following program can be used to call and execute the prepared bat in C #. Assume that the content in test. bat is

Is:

@ Echo off

ECHO we got those parameter % 0, % 1

The following program calls test. bat, passes in the parameter "first", and then passes in with timeout = 45.

View code: Using

 

System;

Using

 

System. Collections. Generic;

Using

 

System. LINQ;

Using

 

System. text;

Using

 

System. diagnostics;

Namespace

 

Leleapplication10

{

 

 

Class Program

{

 

 

Static void main (string [] ARGs)

{

Executeprocess (

"Test. Bat", "first", 45 );

}

 

 

 

Public static void executeprocess (string filename, string arguments, int timeout)

{

 

 

Using (process cmd = new process ())

{

 

 

Console. writeline ("executing: {0} {1}", filename, arguments );

Cmd. startinfo. useshellexecute =

False;

Cmd. startinfo. redirectstandarderror =

True;

Cmd. startinfo. redirectstandardoutput =

True;

Cmd. startinfo. createnowindow =

True;

Cmd. startinfo. filename = filename;

Cmd. startinfo. Arguments = arguments;

Cmd. Start ();

Cmd. waitforexit (timeout );

 

 

If (! Cmd. hasexited)

{

Cmd. Kill ();

 

 

Console. writeline (string. Format ("executeprocess stdout: {0}", cmd. standardoutput. readtoend ()));

 

 

Console. writeline (string. Format ("executeprocess stderr: {0}", cmd. standarderror. readtoend ()));

 

 

Throw new exception ("executeprocess times out .");

}

 

 

If (0! = Cmd. exitcode)

{

 

 

Console. writeline (string. Format ("executeprocess stdout: {0}", cmd. standardoutput. readtoend ()));

 

 

Console. writeline (string. Format ("executeprocess stderr: {0}", cmd. standarderror. readtoend ()));

 

 

Throw new exception ("executeprocess fails .");

 

}

}

}

}

 

The execution result is:

Executing: Test. bat first

Press any key to continue...

 

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.