Today I want to show you one of my tools, which helps developers to handle command line arguments in their Console apps.
How often did you write code for command line handling of your console apps? And how often do you have a Déjà-vus when typing
Ending in a big main-method cluttered up with command line processing mixed with some business logic between the argument-checks.
After the n-th implementation with slightly different but almost the same code, I decided to consolidate the command line handling stuff in a dedicated nuget package.
The basic idea
To pass external value to the app, we’ll use a consistent format, so that each value is passed in with the same syntax nomenclature. As each parameter follows the same syntax rules, we can define a generic analyzer and define a handler for each recognized value. For example:
> myapp.exe -i=data.xml -o=plaintext.txt
myapp program is called with the two arguments
-o=plaintext.txt. Both arguments follow the pattern:
Actually, we do not want to write code handling the parsing of the previous pattern. We also don’t want to take care of changing the equal character in the pattern with a colon or replacing the minus sign with a slash.
This is where SmartCon comes to the rescue 🙂
You can install the package from nuget.org via
> dotnet add package SmartCon
or from the package manager via running
> Install-Package SmartCon
The basic pattern for handling command line arguments looks like this:
The compiled binary can be now called for example with the following parameters:
> MyApp.exe -f=data.csv
This will call the
ReadFile method and pass the value
data.csv as the
The default command line pattern is:
-<key>=<value>. This can be changed by setting the
CommandlineDescription property of the
SmartCon comes with a set of patterns covering the most usual flavours:
// -f=file.txt handler.CommandLineDescription = CommandLineDescription.DefaultCommandLine; // -f:file.txt handler.CommandLineDescription = CommandLineDescription.DotNetStyle; // /f file.txt handler.CommandLineDescription = CommandLineDescription.CmdStyle; // --f=file.txt handler.CommandLineDescription = CommandLineDescription.GnuStyle
Source is available via Github, package available via nuget.org: