16

I want to run a shell command from C# and use the returning information inside my program. So I already know that to run something from terminal I need to do something like that:

string strCmdText;
strCmdText= "p4.exe jobs -e";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);

so now command executed, and from this command some information is returned... My question is how can use this information in my program, probably something to do with command line arguments, but not sure.

I really need to use C#.

Cœur
  • 37,241
  • 25
  • 195
  • 267
inside
  • 3,047
  • 10
  • 49
  • 75
  • See http://stackoverflow.com/q/1585354 – Robert Harvey Mar 05 '13 at 21:28
  • The linked questions tell you how to get the *return value* from a process; this question seems more like it wants the *output* from a program, which is http://stackoverflow.com/questions/14115768/reading-output-from-another-running-application – Michael Edenfield Mar 05 '13 at 22:37

1 Answers1

44

You can redirect the output with ProcessStartInfo. There's examples on MSDN and SO.

E.G.

Process proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

Depending on what you are trying to accomplish you can achieve a lot more as well. I've written apps that asynchrously pass data to the command line and read from it as well. Such an example is not easily posted on a forum.

Community
  • 1
  • 1
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348