如何使用argv在C#中启动子进程?(或将agrv转换为合法的arg字符串)

luc*_*cas 7 c# shell mono subprocess argv

我有一个C#命令行应用程序,我需要在Windows中运行并在单声道下运行unix.在某些时候,我希望在给定一组通过命令行传入的任意参数的情况下启动一个子进程.例如:

Usage: mycommandline [-args] -- [arbitrary program]
Run Code Online (Sandbox Code Playgroud)

不幸的是,System.Diagnostics.ProcessStartInfo仅为args采用字符串.对于以下命令,这是一个问题:

./my_commandline myarg1 myarg2 -- grep "a b c" foo.txt
Run Code Online (Sandbox Code Playgroud)

在这种情况下,argv看起来像:

argv = {"my_commandline", "myarg1", "myarg2", "--", "grep", "a b c", "foo.txt"}
Run Code Online (Sandbox Code Playgroud)

请注意,"ab c"周围的引号被shell剥离,所以如果我简单地连接参数以便为ProcessStartInfo创建arg字符串,我得到:

args = "my_commandline myarg1 myarg2 -- grep a b c foo.txt"
Run Code Online (Sandbox Code Playgroud)

这不是我想要的.

是否有一种简单的方法可以将argv传递给C#OR下的子进程启动,以将任意argv转换为对windows和linux shell合法的字符串?

任何帮助将不胜感激.

luc*_*cas 1

感谢大家的建议。我最终使用了 shquote 的算法(http://www.daemon-systems.org/man/shquote.3.html)。

/**
 * Let's assume 'command' contains a collection of strings each of which is an
 * argument to our subprocess (it does not include arg0).
 */
string args = "";
string curArg;
foreach (String s in command) {
    curArg = s.Replace("'", "'\\''"); // 1.) Replace ' with '\''
    curArg = "'"+curArg+"'";          // 2.) Surround with 's
    // 3.) Is removal of unnecessary ' pairs. This is non-trivial and unecessary
    args += " " + curArg;
}
Run Code Online (Sandbox Code Playgroud)

我只在linux上测试过这个。对于 Windows,您只需连接参数即可。