C# arg parser
Monday, December 2nd, 2013Since I posted a perl one. Note there’s probably some neat way to do this using system libraries that I just don’t know about, but this is what I use
As part of the class (you can have this as a class i.e. Config.cs, or as part of the program:
static readonly DictionaryargsDict = new Dictionary ();
Parser:
static public void ArgHandler(string[] args)
{
foreach (string arg in args)
{
Regex quoteRE = new Regex(“\”(.*)\””);
string[] quoteResults = quoteRE.Split(arg);
string workarg;
if (quoteResults.Length > 1)
{
workarg = quoteResults[1];
}
else
{
workarg = arg;
}Regex argRE = new Regex(“–(.*)=(.*)”);
string[] regResults = argRE.Split(workarg);
if (regResults.Length > 1)
{
Console.WriteLine(string.Format(” — {0} -> {1}”, regResults[1], regResults[2]));
argsDict.Add(regResults[1], regResults[2]);
}
}
}
Get a argument:
static public string GetArg(string arg)
{
string result = null;
argsDict.TryGetValue(arg, out result);
//if (debug)
// Console.WriteLine(“arg ” + arg + ” -> ” + result);
return result;
}
At the top of main(), call:
ArgHandler(args);