When building console applications that take parameters, you can use the arguments passed to Main(string[] args)
.
In the past I've simply indexed/looped that array and done a few regular expressions to extract the values. However, when the commands get more complicated, the parsing can get pretty ugly.
So I'm interested in:
- Libraries that you use
- Patterns that you use
Assume the commands always adhere to common standards such as answered here.
This is a handler I wrote based on the Novell
Options
class.This one is aimed at console applications that execute a
while (input !="exit")
style loop, an interactive console such as an FTP console for example.Example usage:
And the source:
I would suggest the open-source library CSharpOptParse. It parses the command line and hydrates a user-defined .NET object with the command-line input. I always turn to this library when writing a C# console application.
Looks like everybody has their own pet command-line parsers, figure I had better add mine as well :).
http://bizark.codeplex.com/
This library contains a command-line parser that will initialize a class with the values from the command-line. It has a ton of features (I've been building it up over many years).
From the documentation...
Command-line parsing in the BizArk framework has these key features:
C# CLI is a very simple command-line argument parsing library that I wrote. It's well-documented and open source.
CLAP (command line argument parser) has a usable API and is wonderfully documented. You make a method, annotating the parameters. https://github.com/adrianaisemberg/CLAP
I recently came across The FubuCore Command line parsing implementation I really like it, the reasons being:
Below is a simple example on how to use this. To illustrate the usage, I've written a simple utility that has two commands: - add (adds an object to a list - an object consists of a name(string), value(int) and a boolean flag) - list (lists all the currently added objects)
First of all, I wrote a Command class for the 'add' command:
This command takes a CommandInput instance as parameter, so I define that next:
The next command is 'list', which is implemented as follows:
The 'list' command takes no parameters, so I defined a NullInput class for this:
All that's left now is to wire this up in the Main() method, like this:
The program works as expected, printing hints about the correct usage in case any commands are invalid:
And a sample usage for the 'add' command: