Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Last active October 5, 2021 14:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nekomimi-daimao/b91558a23eac62f367e84503e3405a1a to your computer and use it in GitHub Desktop.
minimum Command Line Parser
using System.Collections.Generic;
namespace Nekomimi.Daimao
{
/// <summary>
/// parsing comannd line into a dictionary.
/// </summary>
public static class MiniCommandLine
{
/// <summary>
/// -key value -> (key, value)
/// -key -> (key, null)
/// </summary>
public static Dictionary<string, string> Command => ParseArguments(System.Environment.GetCommandLineArgs());
// ReSharper disable once MemberCanBePrivate.Global
public static Dictionary<string, string> ParseArguments(IReadOnlyList<string> args)
{
const string prefixOption = "-";
var parseArguments = new Dictionary<string, string>();
for (var count = 0; count < args.Count; count++)
{
var key = args[count];
if (string.IsNullOrEmpty(key) || !key.StartsWith(prefixOption))
{
continue;
}
string value = null;
if (count + 1 < args.Count)
{
value = args[count + 1];
if (string.IsNullOrEmpty(value) || value.StartsWith(prefixOption))
{
value = null;
}
}
parseArguments[key.Substring(prefixOption.Length)] = value;
}
return parseArguments;
}
}
}
@nekomimi-daimao
Copy link
Author

Example

// example command line
var commandLineArgs = "-name hachi -type dog -pet";
var argArray = commandLineArgs.Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries);

// [name, hachi]
// [type, dog]
// [pet,  null]
var parsedArg = MiniCommandLine.ParseArguments(argArray);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment