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 :-)