在C#中运行Linux控制台命令

我使用以下代码在C#应用程序中通过Mono运行Linux控制台命令:

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(); 

这按预期工作。 但是,如果我将命令"-c ls -l""-c ls -l""-c ls /path"我仍然会使用-lpath忽略输出。

在为命令使用多个开关时,我应该使用什么语法?

你忘了引用命令。

您是否在bash提示符下尝试以下操作?

 bash -c ls -l 

我强烈建议你阅读这个男人 。 还有getopt手册,因为它是bash用于解析其参数的东西。

它与bash -c ls完全相同的行为bash -c ls为什么? 因为你必须告诉bash ls -l-c的完整参数,否则-l被视为bash的参数。 无论是bash -c 'ls -l'还是bash -c "ls -l"都能达到预期效果。 你必须添加这样的引号:

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