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.

Three 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.
Strings:
Any argument not beginning with /, - or -- is a string. String arguments are matched to names by the order in which they appear. May be mandatory or optional. Mandatory string must be added to the parser before any optional strings.

Here is an example showing usage:

using System;
using JArgs;

namespace demo01
{
class Program
{
static void Main(string[] args)
{
Parser TheParser = new Parser();
TheParser.HelpText = "Demo application to illustrate use of Parser class.";
TheParser.ClientVersion = "0.01";
TheParser.AddSwitch("Recurse",
"Should program recursively access subfolders?");
TheParser.AddValue("Retry",
"How many times should the program retry to read a file?", true);
TheParser.AddValue("Wait",
"How many seconds should we wait if a folder cannot be accessed?", false);
TheParser.AddString("Root",
"Path to the directory tree to process.", true);
TheParser.AddString("Log", "Path to a log file.", false);
TheParser.AddString("ErrorLog", "Path to an error log.", false);
if (!TheParser.Parse())
{
Console.ReadKey();
return;
}
if (TheParser.IsSwitchPresent("Recurse"))
Console.WriteLine("Recurse selected");
// Retry must be present because TheParser returned true.
Console.WriteLine("Retry " + TheParser.GetValue("Retry") + " times");
if (TheParser.IsStringPresent("Log"))
Console.WriteLine("Log file path is: " + TheParser.GetString("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