Parse command line arguments/options in C#

Ralph picture Ralph · Apr 5, 2017 · Viewed 17.6k times · Source

I have a console application with some arguments and options so I would like to use a free third-party library.

I have found two libraries for this purpose: NDesk.Options and Command Line Parser Library

Finally I have decided to use Command Line Parser Library because it is clearer using properties so I have downloaded it and added a reference to it.

The problem is that when adding the reference to my .NET Framework 3.5 project I get a warning icon. From the above page where I have downloaded it, it says that compatibility is .NET Framework 3.5+ so I understand 3.5 is compatible, am I right? If not which previous version of it is compatible with .NET Framework 3.5?

Answer

Denis Voituron picture Denis Voituron · Apr 13, 2017

You can also use the new Microsoft CommandLineUtils library. The nuget package is here, but only for .NET Core or Framrwork 4.5.2. But you can download the source code (only 7 files) and include in your projet. For the Framework 3.5, you have only 2 compilation errors to solve: remove an extra method (using Tasks) and remove one line (in HandleUnexpectedArg).

To use this library, find here a first sample:

static void Main(string[] args)
{
    var cmd = new CommandLineApplication();
    var argAdd = cmd.Option("-a | --add <value>", "Add a new item", CommandOptionType.SingleValue);

    cmd.OnExecute(() =>
    {
        Console.WriteLine(argAdd.Value());
        return 0;
    });

    cmd.HelpOption("-? | -h | --help");
    cmd.Execute(args);            
}