【问题标题】:Running a Linux Console Command in C#在 C# 中运行 Linux 控制台命令
【发布时间】:2014-07-23 12:45:00
【问题描述】:

我正在使用以下代码在 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 /path",我仍然会得到忽略-lpath 的输出。

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

【问题讨论】:

  • 您可以尝试使用ProcessStartInfo.Arguments 看看替代方法是否有效?你还需要 /bin/bash 吗?你不能直接运行'ls'吗?
  • @cjb110 不,它不起作用。是的,您必须将 /bin/bash 设置为文件名,否则它无法自行找到 bash 可执行文件。
  • 也许尝试 RedirectStandardInput 并发送命令。我不知道确切的代码,但我知道您可以这样做以向进程发送输入。这是一个示例:msdn.microsoft.com/en-us/library/…
  • 这个问题有解决办法吗?我也有同样的。

标签: c# mono


【解决方案1】:

您忘记引用该命令。

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

bash -c ls -l

我强烈建议阅读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'");

【讨论】:

  • bash -c 'ls -l' 与 bash -c "ls -l" 几乎相同,但不需要在 C# 字符串中转义
猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多