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

2024-07-03

我使用以下代码在 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" or "-c ls /path"我仍然得到输出-l and path被忽略。

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


你忘了quote命令。

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

bash -c ls -l

我强烈建议阅读man bash http://www.gnu.org/software/bash/manual/bash.html#Invoking-Bash。 还有 getopt 手册,因为 bash 使用它来解析其参数。

它的行为与bash -c ls为什么?因为你必须告诉 bashls -l的完整论证是-c, 否则-l被视为 bash 的参数。 任何一个bash -c 'ls -l' or bash -c "ls -l"会做你所期望的。 您必须添加这样的引号:

ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c 'ls -l'");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中运行 Linux 控制台命令 的相关文章

随机推荐