NDesk.Options - detecting invalid arguments

I use NDesk.Options to parse command line arguments for C # command line. It works fine, except that I want my program to fail, and show the help output if the user includes arguments that I did not expect.

I parse the parameters this way:

var options = new OptionSet { { "r|reset", "do a reset", r => _reset = r != null }, { "f|filter=", "add a filter", f => _filter = f }, { "h|?|help", "show this message and exit", v => _showHelp = v != null }, }; try { options.Parse(args); } catch (OptionException) { _showHelp = true; return false; } return true; 

With this code, if I use the argument incorrectly, for example, specifying --filter without =myfilter after that, then NDesk.Options throws an OptionException, and everything will be fine. However, I also expected that an OptionException would be thrown if I passed an argument that did not match my list, for example --someOtherArg . But this does not happen. The parser simply ignores this and continues to truck.

Is there a way to detect unexpected arguments with NDesk.Options?

+6
source share
1 answer

The OptionSet.Parse method returns unrecognized parameters in the List<string> . You can use this to report unknown parameters.

 try { var unrecognized = options.Parse(args); if (unrecognized.Any()) { foreach (var item in unrecognized) Console.WriteLine("unrecognized option: {0}", item); _showHelp = true; return false; } } catch (OptionException) { _showHelp = true; return false; } return true; 
+10
source

Source: https://habr.com/ru/post/917008/


All Articles