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

rav*_*024 5 c# mono

我使用以下代码在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();
Run Code Online (Sandbox Code Playgroud)

这按预期工作.但是,如果我给出命令,"-c ls -l"或者"-c ls /path"我仍然得到输出-lpath忽略.

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

Fab*_*Fab 3

您忘记引用该命令。

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

bash -c ls -l
Run Code Online (Sandbox Code Playgroud)

我强烈建议阅读man bash。还有 getopt 手册,因为 bash 使用它来解析其参数。

它的行为与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'");
Run Code Online (Sandbox Code Playgroud)

  • bash -c 'ls -l' 与 bash -c "ls -l" 几乎相同,但不需要在 C# 字符串中转义 (2认同)