[Mono-list] shell comands and piping

Michael Hutchinson m.j.hutchinson at gmail.com
Thu Aug 19 13:55:27 EDT 2010


On Wed, Aug 18, 2010 at 8:49 PM, Rampage <atomikramp at email.it> wrote:
> Hello everyone,
> i've browsed the archive but couldn't find any information about this,
> so i hope you can help me out :)
>
> here is my problem:
> i have a method like this:
>
>       public string StartProcess(string sProgram, string sArguments)
>       {
>           Process prc = new Process();
>           prc.StartInfo.UseShellExecute = false;
>           prc.StartInfo.FileName = sProgram;
>           prc.StartInfo.Arguments = sArguments;
>           prc.StartInfo.RedirectStandardOutput = true;
>           prc.Start();
>           string stdout;
>           stdout = prc.StandardOutput.ReadToEnd();
>           return stdout;
>       }
>
> suppose that i run it like this:
> StartProcess("cat", "testfile.txt");
> i would get a string containing the output from cat.
> the problem comes if i want to pipe something
> generally using the shell i would do
> #cat testfile.txt | grep word (i know i can do grep word testfile.txt,
> but it's just for example)
>
> is there a way to use the pipe with forked processes? couse i can't pass
> it as an argument for my program couse it wont work.

Piping simply feeds the standard output of one process to the standard
input of another. You could do this in C# by using
Process.StandardInput.

Alternatively, you could run a shell command using sh:
StartProcess("sh", "-c 'cat testfile.txt | grep word' ");

Best solution IMO would just be to use  .NET APIs, unless the shell
commands are doing particularly complex thing:
var txt = File.ReadAllText ("testfile.txt");
var matches = Regex.Matches (txt, "word");

-- 
Michael Hutchinson
http://mjhutchinson.com


More information about the Mono-list mailing list