Skip to main content

A simple Command Line Arguments Parser in C#.

// Command Line Arguments Parser
// http://volatileread.com/UtilityLibrary?id=1081

//
// CommandLineParser.cs

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace DotnetCommon.Utils
{
    public static class CommandLineParser
    {
        /// <summary>
        /// Simple Command Line Arguments Parser.
        /// </summary>
        /// <param name="args">The command line arguments to parse.</param>
        /// <returns>A Dictionary collection of the parsed key/value args.</returns>
        /// <remarks>Original code from: http://volatileread.com/UtilityLibrary?id=1081</remarks>
        public static IDictionary<string, string> Parse(string args)
        {
            var regex = new Regex(@"(-{1,2}|/)(?<switch>\S*)(?:[=:]?|\s+)(?<value>[^-\s].*?)?(?=\s+[-\/]|$)");

            var matches = (from match in regex.Matches(args)
                select new KeyValuePair<string, string>(match.Groups["switch"].Value,
                    match.Groups["value"].Value)).ToList();

            var result = new Dictionary<string, string>(matches.Count);
            foreach (var match in matches)
            {
                result.Add(match.Key, match.Value);
            }

            return result;
        }
    }
}

//
// CommandLineParserTests.cs

using DotnetCommon.Utils;
using Xunit;

namespace DotnetCommon.Tests.Utils
{
    public class CommandLineParserTests
    {
        [Theory]
        [InlineData("-param1 value1", "param1", "value1")]
        public void SingleArgument_WithHyphen_ShouldReturnNameWithoutHyphen(string args, string expectedResultName, string expectedResultValue)
        {
            var parsedArgs = CommandLineParser.Parse(args);

            Assert.True(parsedArgs.ContainsKey(expectedResultName));
            Assert.Equal(expectedResultValue, parsedArgs[expectedResultName]);
        }

        [Theory]
        [InlineData("-param1", "param1", "")]
        public void SingleArgument_WithNoValue_ShouldReturnNameWithEmptyStringValue(string args, string expectedResultName, string expectedResultValue)
        {
            var parsedArgs = CommandLineParser.Parse(args);

            Assert.True(parsedArgs.ContainsKey(expectedResultName));
            Assert.Equal(expectedResultValue, parsedArgs[expectedResultName]);
        }

        [Theory]
        [InlineData(@"-fileName ""C:\Some Folder With Space\Some File.ext\""", "fileName", @"""C:\Some Folder With Space\Some File.ext\""")]
        public void ArgumentsWithSpaces_SurroundedByQuotes_ShouldReturnFullValueWithQuotes(string args, string expectedResultName, string expectedResultValue)
        {
            var parsedArgs = CommandLineParser.Parse(args);

            Assert.True(parsedArgs.ContainsKey(expectedResultName));
            Assert.Equal(expectedResultValue, parsedArgs[expectedResultName]);
        }
    }
}