Run shell commands using c# and get the info into

2019-01-11 08:11发布

问题:

This question already has an answer here:

  • Get return value from process 2 answers
  • Reading output from another running application 3 answers

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 know that it much easier to do it with script languages such as python, but really need to use c#

回答1:

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.



标签: c# .net shell