views:

131

answers:

2

Good Day,

As 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 Programm 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!

Elektro

+1  A: 

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();
Brian Rasmussen
A: 

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.

Gilles
sorry, im used to say bash but i want Windows cmd Batch skript
Thomas
tank you, your code is working nicely. Two bits: At line 7 there is an bracket to much. Second bit: after path_to_script you just leave a blanket and you can add your arguments to the script. Thank you all a lot , my boss is very happy :D
Thomas