# Monday, April 07, 2008
« ReSharper NUnit Failing Silently | Main | XML Data Migrations for SQL Server »

It seems like we've all done this a hundred times before.  I know I have.  What I really want is a strongly typed argument object passed in from the command line, but all we get is a bunch of strings to parse through.  Yuck, I hate parsing strings.

There are a few existing command line parsing libraries in .NET.  I thought about using one of them, but I either ran into licensing issues, old .NET 1.1 code, or the library was just too big and over complicated for what I wanted.

Needing this functionality yet again, I decided to create a re-usable library that allows me to create my command line arguments via property attributes.  To create a new argument class I just apply a SwitchAttribute to each property I want settable from the command line.

    public class Options
    {
        private int port;
 
        [Switch("Port", "Sets the IP Address port of the server.")]
        public string Port
        {
            get { return port; }
            set { port = value; }
        }
    }

 

Then to use this options class from my console application, I only need to:

    private static int Main(string[] args)
    {
        CommandLineParser parser = new CommandLineParser(args);
        Options options = parser.BuildOptions(new Options());
 
        if (options.Port != 0)
        {
            // ...
        }
    }

 

As you can see, this is nothing fancy, but it makes building new console apps a little easier, and more importantly it makes adding or changing command line arguments much more maintainable since I only need to modify a single property forgoing any string parsing.  I can also get a nicely formatted list of what command line arguments are available along with their descriptions.

    foreach (string line in CommandLineParser.GetUsageLines(new Options()))
        System.Console.WriteLine(line);

 

Outputs:

/Port    Sets the IP sddress port of the server.
/Server   Sets the name of IP address of the server.
...

 

If you interested in using the library, its available in my Google code SVN repository under the Apache 2.0 license.

Comments are closed.