Posted on Wednesday June 17, 2009

Command line arguments parser

There are already 2 or 3 command line arguments in C#, two of which are found on the website. Both of these didn’t match my exact needs so I decided to write my own one.

An updated and more advanced parser can be found in the CommandOptions class.

The format is the Unix bash command line format, not the Windows forward slash format.

The one below doesn’t use regular expressions (mostly from realising I could do it faster tokenizing than failing with the regex syntax for hours). It’s implemented using a basic state machine, it could probably be improved to use the State pattern, but works fine for now. I haven’t researched the optimum way for token parsing, as I’m sure there are proven methods for doing it. If you know any sites or examples of these (Douglas Crokford’s JSLint is one example I know), contact me on the contact page.

Without specifying the args, the class automatically grabs the command line from the System.Environment.CommandLine property, and removes the current process name from this.

Correct formats it accepts are:

-arg1=value -arg2=value
-arg=’my value’
-arg=”my value”
-arg=1,2,3,4 -arg2=another

Incorrect formats it won’t accept are:

-arg1 = value
-arg1 value
-arg1 “value value”

Here’s the source, with example usage: