Introducing the Command Line Parser Library to make parsing command line arguments easier
November 10, 2015 3 Comments
If you’ve worked extensively with .NET console applications then you’ve probably encountered difficulties with parsing the command line arguments. They are passed into the args argument of the Main function. Then it’s your task to investigate if the caller has passed in all necessary arguments:
- Have all the mandatory arguments been passed in?
- What default value do we take for optional arguments?
- What about the ordering of arguments?
…et cetera, the list could grow a lot longer.
Fortunately there are libraries that can help you parse the arguments. One such library is called Command Line Parser Library available from NuGet here. You can find its project page here with some initial code examples.
You can install the library from within Visual Studio:
Upon installation you’ll see a readme.txt file in Visual Studio with some extra code examples.
The most basic usage of the library is that you create a custom class that will hold the argument properties. E.g. if your application requires a name and an age argument then you create a class with those properties and decorate them with attributes from the parser library.
Let’s see how it works in code.
Consider the following class:
public class ProgramArguments { [Option('n')] public string Name { get; set; } [Option('a')] public int Age { get; set; } }
The Option attribute has a range of overloaded versions and named arguments. The above example means that Name will be populated with the argument preceded by “-n”. The same is “-a” for the Age. It is very common to indicate the role of an argument:
myapplication -n “Andras” -a 36
The ordering shouldn’t matter:
myapplication -a 36 -n “Andras”
The parser library can handle that of course.
You can populate the ProgramArguments object properties as follows:
static void Main(string[] args) { ProgramArguments arguments = new ProgramArguments(); CommandLine.Parser.Default.ParseArguments(args, arguments); }
Providing the arguments…
-n “Andras” -a 36
…to the application will in fact correctly populate the Name and Age properties of the ProgramArguments object.
The library can handle a lot of different cases.
View all various C# language feature related posts here.
Pingback: Introducing the Command Line Parser Library to make parsing command line arguments easier | Dinesh Ram Kali.
Thanks Andras, your code worked like a charm
It’s telling me it can’t convert from my version of Program Arguments to System.type.