Search code examples
c#console-applicationcommand-line-arguments.net-6.0system.commandline

C# - Console App - How To Read CLI option arguments


Using the System.CommandLine v.2.0.0-beta3.22114.1 and System.CommandLine.NamingConventionBinder v.2.0.0-beta3.22114.1, I'm attempting to create a simple get command with a --name option.

The option is required. It expects an argument, and it will use it in the Console.WriteLine statement.

For the sake of organization, I am creating the commands in separate class files and inherit the Command class.

public class GetCommand : Command
{
    public GetCommand()
        :base("get", "Filters events by name.")
    {
        var name = new Option("--name", "The name of the event you like to fetch.")
        {
            IsRequired = true,
        };

        AddOption(name);
        Handler = CommandHandler.Create((string name) => Console.WriteLine(name));

        
    }
}

While running the app, when I run the executable with the get --name ali command, option, and argument, I keep getting the following exception: Unrecognized command or argument 'ali'.

What am I doing wrong?


Solution

  • For options that take an argument, you should use the generic Option<T>. Use the type of the argument as the type parameter:

    new Option<string>(
        name: "--name", 
        description: "The name of the event you like to fetch."
    ) {
        IsRequired = true
    }