Command line parser for .net

I just wrote a command line parser for .net which parses the command line similar to the way Monad’s cmdlets do it, with the key difference that this still is for the normal .exe executables.

It’s very simple, first get yourself a program class, which contains some properties you want the user able to set via the commandline and apply the Parameter attribute:

class CopyProgram
{
    private string _Source;
    [Parameter(Position = 0, IsMandatory = true)]
    public string Source
    {
        get { return _Source;}
        set { _Source = value; }
    }
    private string _Target;
    
    [Parameter(Position = 1, IsMandatory = true)]
    public string Target
    {
        get { return _Target;}
        set { _Target= value; }
    }
    
    private bool _WalkRecursivly;
    [Parameter(Name = "recursivly")]
    public bool WalkRecursivly
    {
        get { return _WalkRecursivly;}
        set { _WalkRecursivly= value; }
    }   

    static void Main(string[] args)
    {
        new Program().Run(args);
    }

    void Run(string[] args)
    {
        CommandLine.ParseCommandLine(args, this);
        
        // Do stuff here
    }
}

The CommandLine.ParseCommandLine function takes care of parsing the command line string array and filling the required properties of the class provided.

You can call this program in a few different ways:

copy.exe c:\source.txt c:\target.txt
copy.exe -s c:\source.txt -target c:\target.txt
copy.exe -targ c:\target.txt c:\source.txt  -r

Although it only required around 250 lines of code it certainly is an enourmous time safer and makes stuff a lot easier for the user.

At the moment I’m programming a few small utilities and will change the code a bit and fix some bugs if any.

For those interesting in testing it themselves (I encourage it), just download the Intrepid.Corelib .net 2 assembly*. The classes required are in the Intrepid.Automation namespace. Please send any bug reports to: bas.westerbaan@gmail.com.

(* You may use everything in the Intrepid.Corelib assembly freely for non-commercial open-source usage. Do not modify or reverse engineer the assembly in any way.)

Update:
Got rid of some bugs and added the RequiresValue property to ParameterAttribute. Will replace lateron with Type, this allows you to use -e bleh where -e takes no value and bleh is interpreted as a nameless parameter. Will add alliases too.

Tags: , ,

One Response to “Command line parser for .net”

  1. Alex Angelopoulos says:

    Bas, it looks like the download for this is no longer online. Any chance you can post it again? I’ve recently run into a few people trying to reinvent this particular wheel (including the INI parser elements), and want to point them to your download instead of just passing on the binary that I have.

Leave a Reply