Simple C# Command Line Argument Parser

I occasionally write simple console applications, and each time I ‘re-invent the wheel’ by hand-coding routines to retrieve and process command line arguments. So I decided to create this library which I could reuse each time.

It is a single dll that allows you to specify programmatically what arguments are excepted then parse those arguments and pass them back to the client code.

Two kinds of argument are implemented.

Switches:
Used for Boolean items. For example /Recurse to recurse. -Recurse and --Recurse are also recognised. The user may abbreviate switches, for example /R, as long as no ambiguity arises.
Values:
Used for names or values. For example /delay=10 or /path=c:\test. Abbreviations such as -del=10 and --d=10 are also recognised. Values may be mandatory or optional.

Support?

(This paragaraph was added in June 2018, eighteen months after this code was written and a year after it was uploaded to web.)

Since writing this code, my life has changed, and I no longer code. Life moves on, I guess! Consequently my C# sharp skills have faded as has my familiarity with this code.

As you may have figured, this is a roundabout way of saying that I DO NOT OFFER SUPPORT! Sorry folks. I lived this stuff two years ago. But today it makes my brain hurt. So please don't e-mail me asking for help.

Sorry. I'm an old guy. Cut me some slack!


Here is an example showing usage:

using System;
using JArgs2;

namespace demo03
{
class Program
{
static void Main(string[] args)
{
// Create a parser.
Parser P = new Parser("demo03.exe","0.01","Help text goes here.");
// Add expected items to the parser.
P.AddSwitch("Recurse",
"Should program recursively access subfolders?");
P.AddValue("Retry",
"How many times should the program retry to read a file?", true);
P.AddValue("Wait",
"How many seconds should we wait if a folder cannot be accessed?", false);
P.AddValue("Root",
"Path to the directory tree to process.", true);
P.AddValue("Log", "Path to a log file.", false);
P.AddValue("ErrorLog", "Path to an error log.", false);
// Run the parser.
if (!P.Parse())
{
Console.WriteLine("Incorrect arguments.");
Console.ReadKey();
return;
}
// See which arguments were entered.
if (P.IsItemPresent("Recurse"))
Console.WriteLine("Recurse selected");
// Retry must be present because item was mandatory
// and P returned true.
Console.WriteLine("Retry " + P.GetValue("Retry") + " times");
if (P.IsItemPresent("Log"))
Console.WriteLine("Log file path is: " + P.GetValue("Log"));
Console.ReadKey();
}
}
}

Click here to download the dll.

Click here to download the source code to compile it yourself.

Click here for a document explaining how to use it.

www.the-roberts-family.net