Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does CommandLine.Parser support multiple occurences of an option?

How can I support this using CommandLine.Parser ?

program.exe -s file1 -t file2 -t file3
like image 584
Serge Wautier Avatar asked Oct 26 '25 09:10

Serge Wautier


1 Answers

Yes. That's possible with an IEnumerable:

class Program
{
    static void Main(string[] args)
    {
        args = new[] { "-s", "sourceFile", "-t", "targetFile1", "targetFile2" };

        Parser.Default.ParseArguments<MyOptions>(args).WithParsed(o =>
        {
            foreach (var target in o.Targets)
            {
                Console.WriteLine(target);
            }
        });

        Console.ReadKey();
    }
}

internal class MyOptions
{
    [Option('s')]
    public string Source { get; set; }

    [Option('t')]
    public IEnumerable<string> Targets { get; set; }
}

The cool thing is, you can even use FileInfo and DirectoryInfo with the CommandLine.Option attribute.

There is also support for multiple instances of the same option:

args = new[] { "-s", "sourceFile", "-t", "targetFile1", "targetFile2", "-t", "targetFile3" };

Parser parser = new Parser(settings =>
{
    settings.AllowMultiInstance = true;
});

parser.ParseArguments<MyOptions>(args).WithParsed(...
like image 176
kapsiR Avatar answered Oct 28 '25 22:10

kapsiR



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!