Alex Rivera | Logout

Reading Batch shell script output into C# .Net Program

Asked 2010-09-18T14:41:44.860
17

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!

Edit
Report

1 Answer

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.

answered 2010-09-18T15:46:23.593

Your Answer