【问题标题】:Parsing command-line options in C# [duplicate]在 C# 中解析命令行选项 [重复]
【发布时间】:2011-03-20 03:07:16
【问题描述】:

我见过人们编写自定义类来更轻松地处理各种语言的命令行选项。我想知道 .NET(3.5 或更低版本)是否内置了任何内容,这样您就不必自定义解析以下内容:

myapp.exe 文件=text.txt

【问题讨论】:

  • 乔恩,我同意 - 在这里发布答案之前没有看到这个问题。我会在那里交叉发布我的答案(我很惊讶到目前为止还没有人提到 CSharpOptParse)。

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


【解决方案1】:

编辑:否。

但是人们已经构建了一些解析器,例如......

可以说是最好的:C# Command Line Argument Parser

【讨论】:

  • 我的意思是内置到框架中,但是谢谢。
【解决方案2】:

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

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))));

【讨论】:

    【解决方案3】:

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

    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);
    

    【讨论】:

      【解决方案4】:

      如果你不喜欢使用库,而简单的东西已经足够好了,你可以这样做:

      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=");
      

      ;

      【讨论】:

        【解决方案5】:

        对于不需要任何复杂功能的快速而肮脏的实用程序,控制台应用程序通常采用以下形式的命令行:

        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();
        

        【讨论】:

          猜你喜欢
          • 2015-02-28
          • 2017-08-31
          • 2012-01-06
          • 2013-02-15
          • 1970-01-01
          • 2015-09-20
          • 2012-08-18
          • 1970-01-01
          • 2015-07-06
          相关资源
          最近更新 更多