NDesk.Options - detect invalid arguments

c#, command-line-arguments

Solution

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;

Problem

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?

Original source