commandline icon indicating copy to clipboard operation
commandline copied to clipboard

Getting details about each CommandLine.Error that WithNotParsed() exposes

Open ghost opened this issue 8 years ago • 0 comments

Here is some basic scaffolding code I'm starting with (CommandLineOptions is the class that will contain the parsed command-line arguments):

/*
using CommandLine;

namespace SampleNamespace
{
    class CommandLineOptions
    {
        [Option(HelpText = @"When set to ""true"", running the application will not make any changes.", Required = false)]
        public bool Preview { get; set; }
    }
}
*/

// Set the CommandLineParser configuration options.
var commandLineParser = new CommandLine.Parser(x =>
{
    x.HelpWriter = null;
    x.IgnoreUnknownArguments = false;
    x.CaseSensitive = true;
});

// Parse the command-line arguments.
CommandLineOptions options;
var errors = new List<CommandLine.Error>();

var parserResults = commandLineParser.ParseArguments<CommandLineOptions>(args)
    .WithNotParsed(x => errors = x.ToList())
    .WithParsed(x => options = x)
;

if (errors.Any())
{
    errors.ForEach(x => Console.WriteLine(x.ToString()));
    Console.ReadLine();
    return;
}

// Parsing successful; the [options] variable should now contain valid argument data.
// The rest of the program code would go here.

Right now, the parser will raise an UnknownOptionError error when I pass a -PreviewX command-line argument, because no PreviewX property exists in the CommandLineOptions class. However, when I loop through the errors using errors.ForEach(x => Console.WriteLine(x.ToString())), I can only see the UnknownOptionError error type; there's no indication that parsing the previewx argument was the cause of the error.

How can I get the previewx string associated with the UnknownOptionError value?

ghost avatar Feb 06 '17 17:02 ghost