Parsing console args

It’s typical for a console app to be driven by args. Often these can be a complex set, e.g. MyApp.exe title:=bob maxSize:=300 outputFile:=results.txt

I keep re-using the following code, so I thought I’d share it;

var commands = CommandsFromArgs(args);
if (commands.ContainsKey("maxSize))
   var maxSize = commands["maxSize"];

/// <summary>
/// Commands from arguments.
/// </summary>
/// The arguments.
/// dictionary of commands
private static Dictionary<string,string> CommandsFromArgs(string[] args)
    var commands = new Dictionary();
    var splitter = new string[] { ":=" };
    foreach (var arg in args)
        if (arg.Contains(":="))
            var pair = arg.Split(splitter, StringSplitOptions.None);
            if (pair.Length == 2)
                commands.Add(pair[0], pair[1]);

    return commands;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s