Reading Batch shell script output into C# .Net Program

23,604

Solution 1

Your ways are good. But you only get the whole Output at the end. I wanted the output when the script was running. So here it is, first pretty much the same, but than I twised the output. If you have problems look at: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx

public void execute(string workingDirectory, string command)
{   

    // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
    // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
    System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(workingDirectory + "\\" + "my.bat ", command);

    procStartInfo.WorkingDirectory = workingDirectory;

    //This means that it will be redirected to the Process.StandardOutput StreamReader.
    procStartInfo.RedirectStandardOutput = true;
    //This means that it will be redirected to the Process.StandardError StreamReader. (same as StdOutput)
    procStartInfo.RedirectStandardError = true;

    procStartInfo.UseShellExecute = false;
    // Do not create the black window.
    procStartInfo.CreateNoWindow = true;
    // Now we create a process, assign its ProcessStartInfo and start it
    System.Diagnostics.Process proc = new System.Diagnostics.Process();

    //This is importend, else some Events will not fire!
     proc.EnableRaisingEvents = true;

    // passing the Startinfo to the process
    proc.StartInfo = procStartInfo;

    // The given Funktion will be raised if the Process wants to print an output to consol                    
    proc.OutputDataReceived += DoSomething;
    // Std Error
    proc.ErrorDataReceived += DoSomethingHorrible;
    // If Batch File is finished this Event will be raised
    proc.Exited += Exited;
}

Something is off, but whatever you get the idea...

The DoSomething is this function:

void DoSomething(object sendingProcess, DataReceivedEventArgs outLine);
{
   string current = outLine.Data;
}

Hope this Helps

Solution 2

Given the updated question. Here's how you can launch cmd.exe to run a batch file and capture the output of the script in a C# application.

var process = new Process();
var startinfo = new ProcessStartInfo("cmd.exe", @"/C c:\tools\hello.bat");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); // do whatever processing you need to do in this handler
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();

Solution 3

You can't capture the output with the system function, you have to go a bit deeper into the subprocess API.

using System;
using System.Diagnostics;
Process process = Process.Start(new ProcessStartInfo("bash", path_to_script) {
                                    UseShellExecute = false,
                                    RedirectStandardOutput = true
                                });
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0) { … /*the process exited with an error code*/ }

You seem to be confused as to whether you're trying to run a bash script or a batch file. These are not the same thing. Bash is a unix shell, for which several Windows ports exist. “Batch file” is the name commonly given to cmd scripts. The code above assumes that you want to run a bash script. If you want to run a cmd script, change bash to cmd. If you want to run a bash script and bash.exe is not on your PATH, change bash to the full path to bash.exe.

Share:
23,604
Thomas
Author by

Thomas

Out of university, thanks to stack overflows answers! Now on the first job - finish a dead projekt. Nobody here thats nows anything anymore. In C#, with i have to learn on the fly. On the side i try to become a TDD Developer. Thank you all for helping stackoverflow and by that helping my career! Thomas

Updated on August 09, 2022

Comments

  • Thomas
    Thomas almost 2 years

    For a project I am building a new front end for an old Batch script System. I have to use Windows XP and C# with .Net. I don't want to touch this old Backend system as it's crafted over the past Decade. So my Idea is to start the cmd.exe Program and execute the Bash script in there. For this I will use the "system" function in .Net.

    But I also need to read the "Batch script commandline Output" back into my C# Program. I could redirect it into a file. But there has to be a way to get the Standard Output from CMD.exe in into my C# Program.

    Thank you very much!