Running a Linux Console Command in C#

2019-05-03 07:10发布

问题:

I am using the following code to run a Linux console command via Mono in a C# application:

ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c ls");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

String result = proc.StandardOutput.ReadToEnd();

This works as expected. But, if i give the command as "-c ls -l" or "-c ls /path" I still get the output with the -l and path ignored.

What syntax should I use in using multiple switches for a command?

回答1:

You forgot to quote the command.

Did you try the following on the bash prompt ?

bash -c ls -l

I strongly suggest to read the man bash. And also the getopt manual as it's what bash use to parse its parameters.

It has exactly the same behavior as bash -c ls Why? Because you have to tell bash that ls -l is the full argument of -c, otherwise -l is treated like an argument of bash. Either bash -c 'ls -l' or bash -c "ls -l" will do what you expect. You have to add quotes like this:

ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c 'ls -l'");


标签: c# mono