Anton Danko
Anton Danko

Reputation: 117

How to run a batch file with C#

I need to run the batch file, wait for it to finish and end the process. The bat file starts another process that intensively prints data to the console, I need to redirect all the output to a certain method and not to show any windows.

I tried all the options, but every time the bat file process gets the Exited state before the internal process is finished, if I use waitforexit() then the process blocks and freezes when the output of the internal program is finished, please help Bat file is correct, it worked with c++ previously.

here is one of the solutions I tried:

class Program
{
  static string batchFilePath = "example.bat";
  static void Main()
  {
    ProcessStartInfo pInfo = new ProcessStartInfo(batchFilePath);
    pInfo.CreateNoWindow = true;
    pInfo.UseShellExecute = false;
    pInfo.RedirectStandardOutput = true;
    pInfo.RedirectStandardError = true;
    using (Process process = new Process())
    { 
      process.StartInfo = pInfo;
      process.OutputDataReceived += (sender, e) =>
      {
        if (e.Data != null)
        {
          Console.WriteLine("Output: " + e.Data);
        }
      };

      process.ErrorDataReceived += (sender, e) =>
      {
        if (e.Data != null)
        {
          Console.WriteLine("Error: " + e.Data);
        }
      };

      process.Start();
      process.BeginOutputReadLine();
      process.BeginErrorReadLine();

      process.WaitForExit();
    }
  }
}

Content of the Bat file:

db2cmd /i other.bat arg1 arg2 arg3
if %errorlevel% neq 0 exit 1

Upvotes: 0

Views: 2646

Answers (3)

Anton Danko
Anton Danko

Reputation: 117

After I changed the bat file, the program works correctly.

I added "/c" to the db2cmd arguments:

db2cmd /i /c other.bat arg1 arg2 arg3
if %errorlevel% neq 0 exit 1

Upvotes: 0

Teodor Mihail
Teodor Mihail

Reputation: 906

# BATCH FILE
echo "OK"
echo "Very Ok"
echo "Awesome"

In order to run the batch file, the System.Diagnostics native C# library must be used. The batch file will be opened by CMD and the batch file path will be passed as a parameter to it.


static Process p = new Process();

string batch_file_path = "C:\\Users\\Teodor Mihail\\Desktop\\test.bat";

p.StartInfo.FileName = "cmd"; // <-- EXECUTABLE NAME
p.StartInfo.RedirectStandardOutput = true; // <-- REDIRECT THE STDOUT OF THE SCRIPT FROM SCRIPT TO OS, TO SCRIPT TO C# APPLICATION
p.StartInfo.Arguments = "/k \"" + batch_file_path + "\""; // <-- COMMAND TO BE RUN BY CMD '/k', and the content of the command "PATH" 
p.StartInfo.CreateNoWindow = true; // <-- CREATE NO WINDOW
p.StartInfo.UseShellExecute = false; // <-- USE THE C# APPLICATION AS THE SHELL THROUGH WHICH THE PROCESS IS EXECUTED, NOT THE OS ITSELF
p.Start(); // <-- START THE APPLICATION


while(true)
{
    string output = p.StandardOutput.ReadLine();

    if (output.Contains("Awesome"))
    {
        Console.WriteLine("Awesome found");
        p.Kill();
        p.Dispose();
        break;
    }
}

Console.ReadLine();

You can run a loop that listens for a certain input, then kill the process if found.

Upvotes: 1

AYoonesi
AYoonesi

Reputation: 11

You can use the System.Diagnostics.Process class's static Start method. Here's the simplified code:

using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        string batchFilePath = @"C:\Path\To\Your\BatchFile.bat";

        // Start the batch file
        Process.Start(batchFilePath);
    }
}

Upvotes: 0

Related Questions