C# CommandLineParser --help printing then stopping

Fede E. picture Fede E. · Jul 31, 2018 · Viewed 7.7k times · Source

I'm building a C# console app which uses CommandLineParser to get some arguments from cmd.

The library already comes by default with the --help (or help verb) to display help information about each parameter accepted.

Now when I run the --help command I do get the help screen, but then the program continues, but it breaks, as the other default parameters are not set.

Code looks like this:

class Options
{
    [Option('f', "force", Required = false, Default = false,
        HelpText = "Force ....")]
    public bool Force { get; set; }

    [Option('v', "version", Required = false, Default = "",
        HelpText =
            "....")]
    public string Version { get; set; }

    [Option('s', "silent", Required = false, Default = false, HelpText = "Disables output ...")]
    public bool Output { get; set; }

    [Option('p', "path", Required = false, Default = "../some/dir/",
        HelpText =
            "Specifies the path ...")]
    public string StartPath { get; set; }
}

Then in the program:

static int Main(string[] args)
{

    try
    {

        var opts = new Options();

        Parser.Default.ParseArguments<Options>(args).WithParsed(parsed => opts = parsed);

        string version = opts.Version;

        PATCH_LOCATION = opts.StartPath;

        ....

So I get the help screen, and then the program keeps running (breaks as opts.StarPath is not set, neither is any of the other defaults).

Any idea how to "exit" the program when the "help" command is received?

NOTE: CommandLineParser also throws a help screen if an unknown parameter is used, which should also exit the program.

Answer

Jon Skeet picture Jon Skeet · Jul 31, 2018

You should check the ParseResult returned by WithParsed:

var result = Parser.Default
    .ParseArguments<Options>(args)
    .WithParsed(parsed => opts = parsed);
if (result.Tag == ParserResultType.NotParsed)
{
    // Help text requested, or parsing failed. Exit.
    return 1;
}

(I believe that requesting help is equivalent to failed parsing. Definitely worth checking.)