How many times you had to build a console application that must receive various input arguments? I know I did a lot of times – from small development tools to various applications. And every time there was a big PITA to handle the input arguments. Every time I have reinvented the wheel, every time I had to check for the arguments, parse them, output various help messages etc.
Recently I came across a library that is designed to handle exactly these kinds of situations in a standardized and easy to handle way. Meet the Command Line Parser Library – http://commandline.codeplex.com/ (also available as a NuGet package).
I won’t go deep into the details – you can go to their CodePlex website for the latest information & sample applications.
The whole idea behind the library is that you create a class that will hold the available options as properties. Each of these properties must be decorated with attributes that are used by the library for reading the command line arguments:
- OptionAttribute – this is used to define a flag or any scalar value input
- OptionArrayAttribute – this is used to define an array of input values of same type, separated by space
- OptionListAttribute – this is used to define a list of strings that should be read from the command lien
- ValueList – this is used to input a list of arguments, such as file names or any other items, which do are not passed as options (but typically they are the last arguments to the executable, in the form of a whitespace-delimited list of strings)
All of these attributes (except for ValueList) allow you to specify a short symbol and a long symbol for specifying the option (think of ‘-f’ vs ‘- -file’). Also, for most options you can specify a default value and whether they are mandatory or not.
Additionally, you can define sub-options using the [VerbOption] attributes. This can be used for discriminating between subtasks – for example, say you want to offer the possibility of replacing all files or only newer. You can define a set of options that will allow you to call your executable like this:
my.exe replace –a (or my.exe replace –all)
my.exe replace –n (or my.exe replace –newer)
The framework also has a built-in way of showing help text when the commands are not used correctly or when the application is executed with no arguments.
Anyway, for more information and more complex samples, check out their CodePlex site (http://commandline.codeplex.com/) as well as their github wiki pages (https://github.com/gsscoder/commandline/wiki).