2

How can I support this using CommandLine.Parser ?

program.exe -s file1 -t file2 -t file3
Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
  • 1
    [Yes](https://github.com/commandlineparser/commandline/wiki/Unparsing). Do you need the `-t` switch two times? – kapsiR Apr 07 '20 at 12:15
  • @kapsiR Ha OK, as simple as backing the option with a collection. Thanks, that's what I was looking for. No I don't explicitely need -t several times. – Serge Wautier Apr 07 '20 at 12:25
  • Would be great if you mark my answer as accepted answer if it works for you Thanks – kapsiR Apr 07 '20 at 14:31

1 Answers1

4

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(...
kapsiR
  • 2,720
  • 28
  • 36
  • The thing is that your answer does not solve the question as the author requested an option should be present multiple times and `-t X Y` is not the same as `-t X -t Y` which seems to fail even if the wiki states that it should work with version 2.9+. – ViRuSTriNiTy Nov 27 '20 at 08:14
  • 1
    @ViRuSTriNiTy: That's why I asked the author of the question via the comments first ;) – kapsiR Nov 27 '20 at 12:58
  • I'm trying to solve this same problem; it would be great to have `-t X -t A,B,C` give me an enumerable with `X,A,B,C`. Is it not possible? – MikeB May 08 '23 at 22:30
  • @MikeB I added an example for multiple instance support – kapsiR May 09 '23 at 14:14