Skip to main content

C# helper method to parse a URL query string into a key/value Dictionary.

/// <summary>
/// Parse the http query string into key/val dictionary.
/// </summary>
/// <param name="query">Http query string.</param>
/// <returns></returns>
public static IDictionary<string, string> ParseQueryString(string query)
{
    Dictionary<string, string> retVal = new Dictionary<string, string>();
    if (string.IsNullOrEmpty(query))
    {
        return retVal;
    }

    if (query.StartsWith("?", StringComparison.Ordinal))
    {
        if (query.Length == 1)
        {
            return retVal;
        }

        query = query.Substring(1);
    }

    string[] valuePairs = query.Split('&');
    foreach (string pair in valuePairs)
    {
        string key;
        string value;

        int equalDex = pair.IndexOf("=", StringComparison.Ordinal);
        if (equalDex < 0)
        {
            key = string.Empty;
            value = Uri.UnescapeDataString(pair);
        }
        else
        {
            key = Uri.UnescapeDataString(pair.Substring(0, equalDex));
            value = Uri.UnescapeDataString(pair.Substring(equalDex + 1));
        }

        string existingValue;
        if (retVal.TryGetValue(key, out existingValue))
        {
            retVal[key] = string.Concat(existingValue, ",", value);
        }
        else
        {
            retVal[key] = value;
        }
    }

    return retVal;
}