【问题标题】:C# - Split executable path and arguments into two stringsC# - 将可执行路径和参数拆分为两个字符串
【发布时间】:2015-07-01 20:25:58
【问题描述】:

我一直在做一些谷歌搜索,但没有找到任何解决方案。路径参数组合的最常见情况有引号,如

"C:\Program Files\example.exe" -argument --argument -argument "argument argument"

"C:\Program Files\example.exe" /argument /argument /argument "argument argument"

他们只是遍历整个事情,寻找第二个引用,然后将其后的所有内容都视为一个论点。

.

我发现的第二个解决方案(see here) 不带引号但仅适用于不带空格的路径。见下文。

这可行:C:\Windows\System32\Sample.exe -args -args -args "argument argument"

这不起作用:C:\Program Files\Sample.exe -argument "arg arg" --arg-arg

这以相同的方式工作。他们查找第一个空格,然后将其后面的所有内容都视为参数,这不适用于某些/大多数程序(程序文件文件夹名称有空格)。

.

有解决办法吗?我尝试过使用和调整许多 sn-ps,甚至尝试制作自己的正则表达式语句,但它们都失败了。代码 sn-ps 甚至库都会派上用场。

提前致谢!

编辑:我根据要求找到的 sn-ps

片段 1:

char* lpCmdLine = ...;
char* lpArgs = lpCmdLine;
// skip leading spaces
while(isspace(*lpArgs))
    lpArgs++;
if(*lpArgs == '\"')
{
    // executable is quoted; skip to first space after matching quote
    lpArgs++;
    int quotes = 1;
    while(*lpArgs)
    {
        if(isspace(*lpArgs) && !quotes)
            break;
        if(*lpArgs == '\"')
            quotes = !quotes;
    }
}
else
{
    // executable is not quoted; skip to first space
    while(*lpArgs && !isspace(*lpArgs))
        lpArgs++;
}
// TODO: skip any spaces before the first arg

来源 2:here 中的几乎所有内容

来源 3:各种阴暗的博客

【问题讨论】:

  • 您的示例包含带空格且不带引号的路径在 Windows 中也不起作用,因此除非您证明这是个问题,否则我不会担心。
  • 只是一个问题:我可以只使用一个字符串 (Process.Start) 来启动一个进程吗?我知道我必须将文件路径和参数分成两个字符串/部分。 (processStarterName.Arguments = "-args -args "参数")

标签: c# regex command-line split arguments


【解决方案1】:

您可以尝试使用 .NET 中唯一板载的 CSV 解析器 VisualBasic.TextFieldParser

List<string[]> allLineFields = new List<string[]>();
var textStream = new System.IO.StringReader(text);
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(textStream))
{
    parser.Delimiters = new string[] { " " };
    parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
    string[] fields;
    while ((fields = parser.ReadFields()) != null)
    {
        allLineFields.Add(fields);
    }
}

对于单个字符串,列表包含一个String[],第一个是路径,其余的是 args。

更新:这适用于除最后一个字符串之外的所有字符串,因为路径是 C:\Program Files\Sample.exe。您必须将其用引号括起来,否则Program Files 中的空格会将它们分成两部分,但这是 Windows 路径和脚本的一个已知问题。

【讨论】:

  • 好的。让我试试看。
  • 好吧,我想我确实需要这些引号。无论如何谢谢:)
  • @PandaLion98:您真的想要一个适用于所有可能格式的解决方案吗?也许您也可以解析该字符串,但它真的需要吗?您想如何找到路径,它与其他路径有什么区别?您不能使用句点,因为它也可能是 C:\Program Files\Sample.Dir\SampleFile.exe。如果你寻找最后一个时期,你可以在论点中找到一个。
  • 无论如何我都会用它来记录日志。这应该不会造成问题。
  • 这行得通。我只是添加了一堆分隔符和一些 if。
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 2012-05-17
  • 2011-06-14
  • 1970-01-01
相关资源
最近更新 更多