In this article, learn how to execute batch files using C# by using Process class of System.Diagnostics namespace.
Execute batch files using C#:
Here there are twl ways you can run batch script using C# code. First by specifying the timeout and secondly by executing the batch file as background process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
. /// <summary> /// Function to execute the batch file. Return the process exit code. /// </summary> public static int RunBatchFile(string batchFilePath, int timeout, bool killOnTimeout = false) { using (Process oProcess = Process.Start(batchFilePath)) { oProcess.WaitForExit(timeout); //Check whether the process executed and exited. Retunr the process exit code. if (oProcess.HasExited) { return oProcess.ExitCode; } //Kill the process incase timeout flag is set true. Otherwise close the main window. if (killOnTimeout) { oProcess.Kill(); } else { oProcess.CloseMainWindow(); } throw new TimeoutException(string.Format("Time allotted for executing `{0}` has expired ({1} ms).", batchFilePath, timeout)); } } |
If you do not wish to mention the timeout, then keep your code simple in this way.
1 2 3 4 5 6 7 8 9 10 11 |
. /// <summary> /// Function to execute the batch file. /// </summary> public static void RunBatchFile(string batchFilePath) { ProcessStartInfo pInfo = new ProcessStartInfo(batchFilePath); pInfo.CreateNoWindow = true; pInfo.UseShellExecute = false; Process.Start(pInfo); } |
– Article ends here –