Sample
public string GetUser()
{
var args = System.Environment.GetCommandLineArgs().ToArgDictionary();
var user = args.GetValueOrDefault("Username", System.Environment.UserName);
return user.ToLower();
}
Extension Method
public static class CommandLineExtensions
{
/// <summary>
/// Returns the value associated with the specified key, or the default value if the key is null or not matched.
/// </summary>
public static string GetValueOrDefault(this Dictionary<string, string> args, string key, string defaultValue)
{
if (string.IsNullOrEmpty(key)) return defaultValue;
key = key.ToLower();
return args.ContainsKey(key) ? args[key] : defaultValue;
}
/// <summary>
/// Creates a Dictionary<<see cref="string"/>, <see cref="T:string[]"/>> from command line arguments.
/// </summary>
public static Dictionary<string, string> ToArgDictionary(this string[] args)
{
var resultDict = new Dictionary<string, string>();
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.Length <= 1) continue;
if (arg[0] != '-') continue;
arg = arg.ToLower();
var parameter = arg.Substring(1);
//Resolve parameter value
var value = string.Empty;
if (parameter.Contains('='))
{
var newParameter = parameter.Substring(0, parameter.IndexOf('='));
value = parameter.Substring(parameter.IndexOf('=') + 1, parameter.Length - (parameter.IndexOf('=') + 1));
parameter = newParameter;
}
else if (i < args.Length - 1 && args[i + 1][0] != '-')
{
value = args[++i];
}
//Set parameter/value to dict
if (!resultDict.ContainsKey(parameter))
{
resultDict.Add(parameter, value);
}
else
{
resultDict[parameter] = value;
}
}
return resultDict;
}
}