Question

I use Stream reader to read context.Request.InputStream to the end and end up with a string looking like

"Gamestart=true&GamePlayer=8&CurrentDay=Monday&..."

What would be the most efficent/"clean" way to parse that in a C# console?

Was it helpful?

Solution

You can use HttpUtility.ParseQueryString

Little sample:

string queryString = "Gamestart=true&GamePlayer=8&CurrentDay=Monday"; //Hardcoded just for example
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

foreach (String k in qscoll.AllKeys)
{
    //Prints result in output window.
    System.Diagnostics.Debug.WriteLine(k + " = " + qscoll[k]);
}

OTHER TIPS

HttpUtility.ParseQueryString

Parses a query string into a NameValueCollection using UTF8 encoding.

http://msdn.microsoft.com/en-us/library/ms150046.aspx

I know this is a bit of a zombie post but I thought I'd add another answer since HttpUtility adds another assembly reference (System.Web), which may be undesirable to some.

    using System.Net;
    using System.Text.RegularExpressions;

    static readonly Regex HttpQueryDelimiterRegex = new Regex(@"\?", RegexOptions.Compiled);
    static readonly Regex HttpQueryParameterDelimiterRegex = new Regex(@"&", RegexOptions.Compiled);
    static readonly Regex HttpQueryParameterRegex = new Regex(@"^(?<ParameterName>\S+)=(?<ParameterValue>\S*)$", RegexOptions.Compiled);

    static string GetPath(string pathAndQuery)
    {
        var components = HttpQueryDelimiterRegex.Split(pathAndQuery, 2);
        return components[0];
    }

    static Dictionary<string, string> GetQueryParameters(string pathAndQuery)
    {
        var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        var components = HttpQueryDelimiterRegex.Split(pathAndQuery, 2);

        if (components.Length > 1)
        {
            var queryParameters = HttpQueryParameterDelimiterRegex.Split(components[1]);

            foreach(var queryParameter in queryParameters)
            {
                var match = HttpQueryParameterRegex.Match(queryParameter);

                if (!match.Success) continue;

                var parameterName = WebUtility.HtmlDecode(match.Groups["ParameterName"].Value) ?? string.Empty;
                var parameterValue = WebUtility.HtmlDecode(match.Groups["ParameterValue"].Value) ?? string.Empty;

                parameters[parameterName] = parameterValue;
            }
        }

        return parameters;
    }

I wish they would add that same method to WebUtility which is available in System.Net as of .NET 4.0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top