简体   繁体   English

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

[英]Running a Linux Console Command in C#

I am using the following code to run a Linux console command via Mono in a C# application: 我使用以下代码在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();

This works as expected. 这按预期工作。 But, if i give the command as "-c ls -l" or "-c ls /path" I still get the output with the -l and path ignored. 但是,如果我将命令"-c ls -l""-c ls -l""-c ls /path"我仍然会得到输出,并忽略-lpath

What syntax should I use in using multiple switches for a command? 在为命令使用多个开关时,我应该使用什么语法?

You forgot to quote the command. 你忘了引用命令了。

Did you try the following on the bash prompt ? 您是否在bash提示符下尝试以下操作?

bash -c ls -l

I strongly suggest to read the man bash . 我强烈建议阅读男人bash And also the getopt manual as it's what bash use to parse its parameters. 还有getopt手册,因为它是bash用来解析其参数的东西。

It has exactly the same behavior as bash -c ls Why? 它与bash -c ls具有完全相同的行为为什么? Because you have to tell bash that ls -l is the full argument of -c , otherwise -l is treated like an argument of bash. 因为你必须告诉bash ls -l-c的完整参数,否则-l被视为bash的参数。 Either bash -c 'ls -l' or bash -c "ls -l" will do what you expect. 无论是bash -c 'ls -l'还是bash -c "ls -l"都可以达到预期效果。 You have to add quotes like this: 你必须添加这样的引号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM