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?
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?
Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.
Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys.
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)
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 ] );
}
}
}
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);
}
}
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;
}