tags:

views:

4961

answers:

6

I would like to parse a string such as "p1=6&p2=7&p3=8" into a NameValueCollection.

What is the most elegant way of doing this when you don't have access to the Page.Request object?

A: 

Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.

Mark Glorie
+1  A: 

Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys.

Bloodhound
+29  A: 

There's a built-in .NET utility for this: HttpUtility.ParseQueryString

//C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

'VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
Guy Starbuck
A: 
    private void button1_Click( object sender, EventArgs e )
    {
        string s = @"p1=6&p2=7&p3=8";
        NameValueCollection nvc = new NameValueCollection();

        foreach ( string vp in Regex.Split( s, "&" ) )
        {
            string[] singlePair = Regex.Split( vp, "=" );
            if ( singlePair.Length == 2 )
            {
                nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );    
            }    
        }
    }
rp
Doh! Thank you Guy Starbuck. I hate it when I work too hard.
rp
semicolon is also allowed as a parameter separator in http, better not to reinvent the wheel
Matthew Lock
+3  A: 

HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}
Scott Dorman
A: 

I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".

I liked rp's answer. I added some additional logic.

public static NameValueCollection ParseQueryString(string s)
    {
        NameValueCollection nvc = new NameValueCollection();

        // remove anything other than query string from url
        if(s.Contains("?"))
        {
            s = s.Substring(s.IndexOf('?') + 1);
        }

        foreach (string vp in Regex.Split(s, "&"))
        {
            string[] singlePair = Regex.Split(vp, "=");
            if (singlePair.Length == 2)
            {
                nvc.Add(singlePair[0], singlePair[1]);
            }
            else
            {
                // only one key with no value specified in query string
                nvc.Add(singlePair[0], string.Empty);
            }
        }

        return nvc;
    }
densom