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

C# 在C中运行Linux控制台命令#,c#,mono,C#,Mono,我使用以下代码在C#应用程序中通过Mono运行Linux控制台命令: ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c ls"); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; System.Diagnosti

我使用以下代码在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();
这正如预期的那样有效。但是,如果我以
“-cls-l”
“-cls/path”
的形式发出命令,我仍然会得到忽略
-l
路径的输出


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

您忘了引用该命令

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

bash -c ls -l
我强烈建议你阅读这本书。 还有getopt手册,因为bash使用它来解析其参数

它的行为与bash-cls
为什么?因为您必须告诉bash,
ls-l
-c
的完整参数,否则
-l
将被视为bash的参数。 无论是
bash-c'ls-l'
还是
bash-c“ls-l”
都能满足您的期望。 您必须添加这样的引号:

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

您可以尝试使用
ProcessStartInfo.Arguments
查看替代方法是否有效?您还需要/bin/bash吗?你不能直接运行“ls”吗?@cjb110不,它不起作用。是的,您必须将/bin/bash设置为文件名,否则它无法单独找到bash可执行文件。请尝试重定向StandardInput并发送命令。我不知道确切的代码,但我知道您可以这样做来向流程发送输入。这里有一个例子:这个问题有解决方案吗?bash-c'ls-l'与bash-c“ls-l”几乎相同,但不需要在c#string中转义