Tuesday, April 26, 2005

Executing a Batch file using C# Code.

Take a look at the Process class in the System.Diagnosticsnamespace.
Namespace - System.Diagnostics
Here is a sample to get you started:

ProcessStartInfo startInfo = null;
Process batchProcess = null;
bool finished = false;
// Write relatively well behaved code for
// service processes.
try {
// Prepare the start-up information for the
// process such as filename to execute, its
// arguments, how to execute and whether to
// redirect input and error.

startInfo = new ProcessStartInfo();
startInfo.Filename = "run.bat";
startInfo.Arguments = "arg1 arg2 arg3 arg4";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
// Start new process using the start info.
batchProcess = new Process();
batchProcess.StartInfo = startInfo();
batchProcess.Start();

// Wait 60 seconds for the process to exit.
finished = batchProcess.WaitForExit(60000);

// If true, the process exited cleanly, if false
// then the process is still running.

if (finished == true) {
// Log that the process exited cleanly.
EventLog.WriteEntry( "The batch process exited cleanly." );
}
else {
// The process didn't exit cleanly so kill
// it off and log the action to the Event Log.
batchProcess.Kill();
EventLog.WriteEntry("The batch process did not exit in time and was killed.");
}
} catch (Exception e)
{
// Things can and will go wrong, at this early
// stage it is probably sufficient to write this to
// the event log. Of course, what do you do if access
// to the event log is denied? Can happen . . .
EventLog.WriteEntry( e.Message);
}

No comments: