web 2.0

Simple Way to Process Command Line Arguments

For some reason I have been finding myself writing more console apps lately. Mostly to overcome unique problems with antiquated systems that rely heavily on batch file processing. Anyway, the most common problem people have when writing console apps is parsing all the arguments that get passed into the program. Since I have already written the code, I thought I would share...

static void ProcessArguments(string[] args) {
    string argString = String.Empty;
    //do a little work to remove unecessary spaces between the option and value
    foreach (string s in args) {
        if (s.StartsWith("-") && argString.Length > 0)
            argString += ",";

        argString += s;
    }

    string[] fixedArgs = argString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

    string pattern = @"-(?<argument>[a-zA-Z])(?<value>.+)#";
    foreach (string argument in fixedArgs) {
        Match match = Regex.Match(argument, pattern, RegexOptions.IgnorePatternWhitespace);
        if (match != null) {
            string option = match.Groups["argument"].Value.ToUpper();
            string value = match.Groups["value"].Value;

            //String.Format( "{0}: {1}", option, value ).WriteDebug();
            if (option == "R") {
                int num;
                if (int.TryParse(value, out num) == true)
                    _retention = num;
            }

            if (option == "P") {
                _filePath = value;
            }
            else if (option == "S") {
                _searchPattern = value;
            }
        }
    }
}

First the code takes all the arguments and puts them to into a format that I can use to apply a regular expression against. For example, the command:

TraceArchiver.exe -p D:\DBA\profiler -s Daily_Thu* -r 7

Would produce an argString value of

-pD:\DBA\profiler,-sDaily_Thu*,-r7

Next, I split this formatted string into an array by using the Split function with the comma as the separator. Then, for each item in the string array I can apply my regular expression pattern against it: For example, if the first item in the string array is "–pD:\DBA\profiler", after the regex pattern (@"-(?<argument>[a-zA-Z])(?<value>.+)#") is applied to it there are two captures created. One titled "argument" and the other called "value".  Now that the string is "tokenized" we are only left with the simple task of checking which argument you are processing and assigning it to a variable. I hope this snippet of code is useful to someone out there. Happy coding :-)

Comments

Michael Ceranski , on 12/17/2009 2:29:09 PM Said:

Michael Ceranski

Cool, I did not know about that library. Thats why it is great when people leave comments.

I guess it boils down to whether or not you want to include a 3rd party library in your code.

Thanks for the comments.

Anonymous , on 12/17/2009 2:29:09 PM Said:

Anonymous

Thanks, I did need something similar to this and it worked perfectly.
Dom

Jaco Pretorius , on 12/17/2009 2:29:09 PM Said:

Jaco Pretorius

What's up with the Java-style brace layout?

Anonymous , on 12/17/2009 2:29:09 PM Said:

Anonymous

I have an even simpler option that I would like to suggest: Mono.GetOptions (or one of the libraries like it, if you aren't happy with GetOptions.)

Command-line parsing has been a solved problem for a number of years now, so there really is no reason to be coding up (and subsequently maintaining!) your own.

Comments are closed