Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.CommandLine parsed values don't match input

I am trying to use System.CommandLine and I haven't been able to get my handler to see any of the values that I'm passing in. I've tried the simplest command line program just to see if any values make it through and so far I haven't been successful. I am targeting .NET 4.7.2 and I'm using System.CommandLine 2.0.0-beta1.20574.7

    using System;
    using System.CommandLine;
    using System.CommandLine.Invocation;

    static class Program
    {
        public static void Main(string[] args)
        {
            var rootCommand = new RootCommand
            {
                new Option("--continue", "continue option")
            };

            rootCommand.Description = "Testing System.CommandLine";

            rootCommand.Handler = CommandHandler.Create<bool>
                ((willContinue) => run(willContinue));

            rootCommand.Invoke(args);
        }

        private static void run(bool willContinue)
        {
            Console.WriteLine(willContinue);
        }
    }

No matter how I call my application, I am not seeing the value of willContinue come across as true.

myapp.exe --continue -> False

myapp.exe --cont -> Unrecognized command or argument '--cont' (my options are at least getting recognized)

myapp.exe --continue true -> Unrecognized command or argument 'true'

myapp.exe --help ->

myapp:
Testing System.CommandLine

Usage:
myapp [options]

Options:
--continue continue option
--version Show version information
-?, -h, --help Show help and usage information

like image 657
TJ Rockefeller Avatar asked Apr 06 '26 01:04

TJ Rockefeller


1 Answers

You need to fix 2 things:

  1. add the option type, which is bool
  2. change the name of the option to match the parameter name

the following command works:

var rootCommand = new RootCommand
{
    new Option<bool>("--willContinue", "continue option")
};

and call it like so

myapp.exe --willContinue true

the option name and parameter name don't always have to match-up, but in this case it doesn't work because 'continue' is a reserved word

like image 174
Lev Avatar answered Apr 08 '26 14:04

Lev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!