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...