Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell commands using C# and get the info into string [duplicate]

Tags:

c#

.net

shell

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#.

like image 280
inside Avatar asked Mar 05 '13 21:03

inside


People also ask

What is a shell command in C?

A simple command is a sequence of words separated by blanks or tabs. A word is a sequence of characters or numerals, or both, that does not contain blanks without quotation marks.

Does C have shell?

The C shell is an interactive command interpreter and a command programming language. It uses syntax that is similar to the C programming language. The csh command starts the C shell.


1 Answers

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.

like image 185
P.Brian.Mackey Avatar answered Oct 12 '22 15:10

P.Brian.Mackey