小编Vis*_*ser的帖子

解析带引号的命令行参数

好的,所以我用空格吐出命令行参数,就像命令提示符一样,但问题是,如果用户尝试输入 DoStuff“有空格但被引用的参数”,它不会正确分割它。我正在使用控制台应用程序。我尝试这样做:baseCommand 是用户输入的未解析的字符串,secondCommand 应该是第二个参数。

int firstQuoteIndex = baseCommand.IndexOf('"');

if (firstQuoteIndex != -1)
{
    int secondQuoteIndex = baseCommand.LastIndexOf('"');
    secondCommand = baseCommand.Substring(firstQuoteIndex, 
        secondQuoteIndex - firstQuoteIndex + 1).Replace("\"", "");
}
Run Code Online (Sandbox Code Playgroud)

这很有效,但首先,它很混乱,其次,如果用户输入如下内容,我不确定如何执行此操作:

DoSomething "second arg that has spaces" "third arg that has spaces"
Run Code Online (Sandbox Code Playgroud)

请记住,如果参数没有引号,则用户不必输入引号。有没有人有什么建议,谢谢。

c# console command-line parsing arguments

2
推荐指数
1
解决办法
2155
查看次数

标签 统计

arguments ×1

c# ×1

command-line ×1

console ×1

parsing ×1