Serge Wautier
Serge Wautier

Reputation: 21878

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

Upvotes: 4

Views: 2421

Answers (1)

kapsiR
kapsiR

Reputation: 3177

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(...

Upvotes: 6

Related Questions