Reporting unknown arguments using CommandLineParser

Is there a way to make the Parser library for the command line report unknown arguments?

Given the following class parameters:

public class Options { [Option('i', "int-option", DefaultValue = 10, HelpText = "Set the int")] public int IntOption { get; set; } [ParserState] public IParserState LastParserState { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, HelpText.DefaultParsingErrorsHandler(this, current)); } } 

And the following program:

 var options = new Options(); var parser = new Parser(settings => { settings.HelpWriter = Console.Error; settings.IgnoreUnknownArguments = false; }); if (parser.ParseArgumentsStrict(args, options)) { Console.WriteLine("Int value set: {0}", options.IntOption); } 

When I call the program with "MyProgram.exe --unknown", I just get the default usage information, but don’t mention which error caused the parsing to fail. I would like to get some indication to the user what went wrong.

+4
source share
1 answer

In short: with the current implementation, you cannot get information about unknown parameters.

Long story:

If you put brakepoint in your GetUsage method, you will see that LastParserState not null, but contains the element 0.

LastParserState is basically populated from ArgumentParser.PostParsingState , but LongOptionParser (which in your case is involved due to the double mark -- ) does not add anything to the PostParsingState collection inside its parsing method:

Github source:

 var parts = argumentEnumerator.Current.Substring(2).Split(new[] { '=' }, 2); var option = map[parts[0]]; if (option == null) { return _ignoreUnkwnownArguments ? PresentParserState.MoveOnNextElement : PresentParserState.Failure; } 

Thus, inside the analyzer does not store information about what went wrong as soon as this fact was recorded.

+3
source

All Articles