Recent Posts
Archives
Topics

Wednesday, January 14, 2009

 

Command Line Parsing

I recently had a case where I needed to handle a series of command line arguments. I needed to know if flagA had been set with flagB, but not with flagC and flagD.

Ripping through the list of command line arguments is easy enough, but tedious, so I wrote my own CommandLine class that lets me reference flags by name. For instance, if I need to check to see if flagA exists, I can just say cmd.ContainsKey("flagA").

The best part is that it only modified my master source by one line:

CMD cmd = new CMD(args);


I thought that this little ditty -- while being trivial in concept -- was worth sharing. If you find it useful, let me know. Also, if you have comments, feel free to post them.


public class CMD : Hashtable
{
public CMD(string[] args)
{
if (args == null) return;

for (int x = 0; x < args.Length; x++)
{
if (args[x].StartsWith("-") || args[x].StartsWith("/"))
{
// take off the "-"
string key = ((string)args[x]).Substring(1);

// We have a flag. Is it a TF or a value flag?
if ((x < args.Length - 1) && (!args[x + 1].StartsWith("-")))
{
// VALUE flag
this[key] = args[x + 1];
x++;
}
else
{
// True/False flag
this[key] = true;
}
}
}
}
}


Once you've defined the class, accessing the command line arguments becomes trivial. In the example below, I have a simple console application that needs command line parsing. Once CMD is initialized, I can access CMD from anywhere, and access all of my command line parameters by name.


class Program
{
static CMD cmd;

static void Main(string[] args)
{
cmd = new CMD(args);

// Do some magic stuff here
}
}

Labels:


Comments:

Post a Comment



Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]