Skip to main content

C# method to parse a string of parameters into key/value Dictionary type.

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

internal static class Program
{
    public static Dictionary<string, string> ParseParameters(string parametersStr)
    {
        var parametersDictionary = new Dictionary<string, string>();

        if (string.IsNullOrEmpty(parametersStr))
        {
            return parametersDictionary;
        }

        char[] trimChars = new char[2]
        {
            '\'',
            '"'
        };

        foreach (Match match in Regex.Matches(parametersStr, "(?<name>[^=]+)=(?<value>[^;]+);?"))
        {
            string str = match.Groups["value"].Value.Trim().Trim(trimChars);
            string key = match.Groups["name"].ToString().Trim().Trim(trimChars);

            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(str))
            {
                if (parametersDictionary.ContainsKey(key))
                {
                    parametersDictionary[key] = str;
                }
                else
                {
                    parametersDictionary.Add(key, str);
                }
            }
        }

        return parametersDictionary;
    }

    // USAGE
    private static void Main()
    {
        var pp = ParseParameters("Name=Jon;Host=localhost;Active=True");
        foreach (KeyValuePair<string, string> keyValuePair in pp)
        {
            Console.WriteLine("Key Parsed: {0}", keyValuePair.Key);
            Console.WriteLine("Value Parsed: {0}", keyValuePair.Value);
            Console.WriteLine();
        }

        Console.ReadKey();
    }
}