bpeterso2000
6/8/2015 - 3:52 PM

The documentation for the CommandLineParser Nuget package at https://commandline.codeplex.com/ is out-of-date. Below is an updated working

The documentation for the CommandLineParser Nuget package at https://commandline.codeplex.com/ is out-of-date. Below is an updated working example of command line parsing, including displaying parsing errors

using System;
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;

namespace CmdLineParser
{
    class Options
    {
        [Option('i', "input", Required = true, HelpText = "Input file to read.")]
        public string InputFile { get; set; }

        [Option('l', "length", DefaultValue = -1, HelpText = "The maximum number of bytes to process.")]
        public int MaximumLength { get; set; }

        [Option('v', null, HelpText = "Print details during execution.")]
        public bool Verbose { get; set; }

        [ValueList(typeof(List<string>), MaximumElements = 2)]
        public IList<string> Items { get; set; }

        [HelpOption]
        public string GetUsage()
        {
            return HelpText.AutoBuild(this, (HelpText current) =>
                HelpText.DefaultParsingErrorsHandler(this, current));
        }

        [ParserState]
        public IParserState LastParserState { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
            var options = new Options();
            var parser = new CommandLine.Parser();
            var result = parser.ParseArguments(args, options);
            if (result)
            {
                if (options.Verbose)
                {
                    Console.WriteLine(options.InputFile);
                    Console.WriteLine(options.MaximumLength);
                }
                else
                    Console.WriteLine("working ...");
            }
            else
            {
                Console.WriteLine(options.GetUsage());
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}