-3

Obviously I can execute something with cmd console using Process.Start();

Is there any way to get output of that process? For example, I could have something like...

Process.Start("sample.bat");

... in my C# winforms application and sample.bat will contain something like:

echo sample loaded 

First Question: is there any way to retrieve that sample loaded, after bat execution? Second question: is there a way to use it without popped up console window?

Ant P
  • 24,820
  • 5
  • 68
  • 105
user2380317
  • 25
  • 1
  • 6
  • See http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx – Jon Jun 03 '13 at 19:22
  • And see http://stackoverflow.com/questions/7459397/how-to-easily-run-shell-commands-using-c – Cameron Jun 03 '13 at 19:23
  • only ask one question in each post – Rune FS Jun 03 '13 at 19:25
  • possible duplicate of [Process.start: how to get the output?](http://stackoverflow.com/questions/4291912/process-start-how-to-get-the-output) – johnc Jun 04 '13 at 02:58

3 Answers3

5

There is an example of exactly how to do this in the Process documentation:

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
James Holderness
  • 22,721
  • 2
  • 40
  • 52
0

Yes, you can use

Process.Start(ProcessStartInfo)

There are a few ways to hook into I/O including ProcessStartInfo.RedirectStandardOutput available. You can use these overloads to read output from your batch files. You can also hook into the Exited event to know when execution is complete.

Use CreateNoWindow for no window.

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
0

Set process.StartInfo.RedirectStandardOutput to true and subscribe to process.OutputDataReceived

using (var process = new Process())
{
    process.StartInfo = new ProcessStartInfo("exename");
    process.StartInfo.RedirectStandardOutput = true;

    process.OutputDataReceived += (s, ev) =>
    {
        string output = ev.Data;
    };


    process.Start();
    process.BeginOutputReadLine();
    process.WaitForExit();
}
BrunoLM
  • 97,872
  • 84
  • 296
  • 452