Search code examples
c#monomonodevelopredhat

How to run a bash command from Mono/MonoDevelop in Red Hat Linux?


I want to run the following bash command using C# and MonoDevelop and store the output to a variable.

./TestApp --H

My MonoDevelop Code:

    Process proc = new Process();
    proc.StartInfo.FileName = "/bin/bash";
    proc.StartInfo.Arguments = "/usr/mono/TestApp  --H";
    proc.StartInfo.UseShellExecute = false; 
    proc.StartInfo.RedirectStandardErrort = true;
    proc.StartInfo.RedirectStandardInput = true;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.Start();
    var output = proc.RedirectStandardOutput.ReadToEnd()

The above code is not working. The output variable is not getting the value as expected.

If I modify the above code by using a shell script, then its working.

Test.sh

    #!/bin/bash
    /usr/mono/TestApp  --H;

Modified Mono Code:

proc.StartInfo.Arguments = "Test.sh";

Thank You


Solution

  • If /usr/mono/TestApp is not a shell script (for your question I guess it is not) this should work (you do not need bash to run programs):

    Process proc = new Process();
    proc.StartInfo.FileName = "/usr/mono/TestApp";
    proc.StartInfo.Arguments = "--H";
    proc.StartInfo.UseShellExecute = false; 
    proc.StartInfo.RedirectStandardError = true;
    proc.StartInfo.RedirectStandardInput = true;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.Start();
    var output = proc.StandardOutput.ReadToEnd ();
    Console.WriteLine("stdout: {0}", output);
    

    By the way, be careful when using redirects. If pipes between TestApp process and Mono process get full, your application will not be able to finish (there is deadlock) Read the documentation for further information: RedirectStandardOutput