How can I obtain the named arguments from a console application in the form of a Dictionary?

前端 未结 4 764
走了就别回头了
走了就别回头了 2021-02-05 05:18

I have a console application called MyTool.exe

What is the simplest way to collect the named arguments passed to this console applicaiton and then to put them in a

4条回答
  •  再見小時候
    2021-02-05 06:16

    Use this Nuget package

    • V1.9.x - Command Line Parser Library (CodePlex - Going away soon and out of date)
    • V2+ - Command Line Parser (Ongoing support)

    Takes seconds to configure and adds instant professional touch to your application.

    // Define a class to receive parsed values
    class Options {
      [Option('r', "read", Required = true,
        HelpText = "Input file to be processed.")]
      public string InputFile { get; set; }
    
      [Option('v', "verbose", DefaultValue = true,
        HelpText = "Prints all messages to standard output.")]
      public bool Verbose { get; set; }
    
      [ParserState]
      public IParserState LastParserState { get; set; }
    
      [HelpOption]
      public string GetUsage() {
        return HelpText.AutoBuild(this,
          (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
      }
    }
    
    // Consume them
    static void Main(string[] args) {
      var options = new Options();
      if (CommandLine.Parser.Default.ParseArguments(args, options)) {
        // Values are available here
        if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);
      }
    }
    

提交回复
热议问题