I am using NDesk.Options to parse command line arguments for a C# command line program. It is working fine, except I want my program to exit unsuccessfully, and show the help output, if the user includes arguments that I did not expect.
I am parsing options thusly:
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 an argument improperly, such as specifying --filter
without =myfilter
after it then NDesk.Options will throw an OptionException and everything will be fine. However, I also expected an OptionException to be thrown if I pass in an argument that doesn't match my list, such as --someOtherArg
. But this does not happen. The parser just ignores that and keeps on trucking.
Is there a way to detect unexpected args with NDesk.Options?
The OptionSet.Parse
method returns the unrecognized options in a List<string>
. You can use that to report unknown options.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With