Reputation: 1201
I'm using System.Diagnostics.Process.Start() to remotely launch commands on a Linux os. Until now I have been able to launch simple commands and then read the output.
For example I can execute the command echo Hello World
and read Hello World
as its output.
Here's the simplified code:
public void Execute(string file, string args) {
Process process = new Process {
StartInfo = {
FileName = file,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
}
To be clearer, I use the code above like this: Execute("echo", "Hello World");
.
Here's my problem: as long as I execute simple commands everything works smooth, but I'd like to launch commands with pipes and redirects, in order to have a stronger control on the command and on its output (without handle the output itself as text).
So, is there a workaround (or maybe a specific library) to achieve this result?
Upvotes: 8
Views: 1756
Reputation: 3417
In order to execute commands in Linux with all the shell features (including pipelines, redirections etc.) use the following code:
public static Process ExecuteInBash(string command)
{
var process = new Process
{
StartInfo =
{
FileName = "bash",
ArgumentList = { "-c", "--", command },
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
return process;
}
Mind that this method is non-blocking, it starts the process and does not wait for it to finish. In order to block you have to call the process.WaitForExit()
method. Also, it is a good idea to check the exit code to find out whether the command succeeded or failed. Example:
var process = ExecuteInBash("echo Hello");
process.WaitForExit();
var standardOutput = process.StandardOutput.ReadToEnd();
var standardError = process.StandardError.ReadToEnd();
if (process.ExitCode == 0)
{
// Command succeeded.
}
Upvotes: 11