How to Execute batch files using C#

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 two ways you can run the batch script using C# code. First by specifying the timeout and secondly by executing the batch file as a background process.

.
/// 
/// Function to execute the batch file. Return the process exit code.
/// 
public static int RunBatchFile(string batchFilePath, int timeout, bool killOnTimeout = false)
{
   using (Process oProcess = Process.Start(batchFilePath))
   {
       oProcess.WaitForExit(timeout);

       //Check whether the process is executed and exited. Return the process exit code. 
       if (oProcess.HasExited)
       {
           return oProcess.ExitCode;
       }
       
       //Kill the process in case the timeout flag is set to 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.

.
/// 
/// Function to execute the batch file.
/// 
public static void RunBatchFile(string batchFilePath)
{
   ProcessStartInfo pInfo = new ProcessStartInfo(batchFilePath);
   pInfo.CreateNoWindow = true;
   pInfo.UseShellExecute = false;
   Process.Start(pInfo);
}


– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Share this: