时间:2010-07-23 14:02:01

标签: c# .net-3.5 command-line-arguments command-line-parsing

5 个答案:

答案 0 :(得分:4)

这是另一种可能的方法。非常简单,但它在过去对我有用。

string[] args = {"/a:b", "/c:", "/d"};
Dictionary<string, string> retval = args.ToDictionary(
     k => k.Split(new char[] { ':' }, 2)[0].ToLower(),
     v => v.Split(new char[] { ':' }, 2).Count() > 1 
                                        ? v.Split(new char[] { ':' }, 2)[1] 
                                        : null);

答案 1 :(得分:2)

对于不需要任何复杂功能的快速实用工具,很多时候控制台应用程序需要使用以下形式的命令行:

program.exe command -option1 optionparameter option2 optionparameter

在这种情况下,要获得“命令”,只需使用args[0]

即可

要获得选项,请使用以下内容:

var outputFile = GetArgument(args, "-o");

GetArgument定义为:

string GetArgument(IEnumerable<string> args, string option)
    => args.SkipWhile(i => i != option).Skip(1).Take(1).FirstOrDefault();

答案 2 :(得分:0)

答案 3 :(得分:0)

这是一篇相当古老的文章,但这是我在所有控制台应用程序中设计和使用的内容。它只是一小段代码,可以注入一个文件中,一切都可以工作。

http://www.ananthonline.net/blog/dotnet/parsing-command-line-arguments-with-c-linq

修改:现在可以在Nuget上使用,它是开源项目CodeBlocks的一部分。

它被设计为声明性和直观地使用,如此(另一个用法示例here):

args.Process(
    // Usage here, called when no switches are found
    () => Console.WriteLine("Usage is switch0:value switch:value switch2"),

    // Declare switches and handlers here
    // handlers can access fields from the enclosing class, so they can set up
    // any state they need.
    new CommandLine.Switch(
        "switch0",
        val => Console.WriteLine("switch 0 with value {0}", string.Join(" ", val))),
    new CommandLine.Switch(
        "switch1",
        val => Console.WriteLine("switch 1 with value {0}", string.Join(" ", val)), "s1"),
    new CommandLine.Switch(
        "switch2",
        val => Console.WriteLine("switch 2 with value {0}", string.Join(" ", val))));

答案 4 :(得分:0)

如果你不喜欢使用图书馆,那么简单就可以做到这一点:

string[] args = Environment.GetCommandLineArgs().Skip(1).ToArray();
Func<string, string> lookupFunc = 
    option => args.Where(s => s.StartsWith(option)).Select(s => s.Substring(option.Length)).FirstOrDefault();

string myOption = lookupFunc("myOption=");