Skip to content

Instantly share code, notes, and snippets.

@leegould
Created March 13, 2012 10:24
Show Gist options
  • Save leegould/2028018 to your computer and use it in GitHub Desktop.
Save leegould/2028018 to your computer and use it in GitHub Desktop.
Command Line Args
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace CommandLineUtils
{
/// <summary>
/// Arguments class.
/// </summary>
/// <seealso cref="http://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser"/>
public class Arguments
{
private static readonly Regex Splitter = new Regex(@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex Remover = new Regex(@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Gets the parameters.
/// </summary>
public Dictionary<string, string> Parameters { get; private set; }
/// <summary>
/// Gets the <see cref="System.String"/> with the specified param.
/// </summary>
/// <value></value>
public string this[string param]
{
get { return Parameters[param]; }
}
/// <summary>
/// Initializes a new instance of the <see cref="Arguments"/> class.
/// </summary>
/// <param name="args">The args.</param>
public Arguments(IEnumerable<string> args)
{
Parameters = new Dictionary<string, string>();
if (args == null) return;
string parameter = null;
foreach (var parts in args.Select(txt => Splitter.Split(txt, 3)))
{
switch (parts.Length)
{
case 1: // Value without parameter
AddToParams(parameter, Remover.Replace(parts[0], "$1"));
parameter = null;
break;
case 2: // Parameter without value
AddToParams(parameter);
parameter = parts[1];
break;
case 3: // Parameter with value
AddToParams(parameter);
AddToParams(parts[1], Remover.Replace(parts[2], "$1"));
parameter = null;
break;
}
}
AddToParams(parameter); // insert last item.
}
private void AddToParams(string parameter, string value = "true")
{
if (parameter != null && !Parameters.ContainsKey(parameter))
{
Parameters.Add(parameter, value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment