How to convert NameValueCollection to a (Query) String
Most ASP.NET developers know that you can get a key/value pair string from the Request.QueryString object (via the .ToString() method). However that functionality isn’t the same for a generic NameValueCollection object (of which Request.QueryString is derived from).
So how do you take a NameValueCollection object and get a nicely formatted key/value pair string? (i.e. “key1=value1&key2=value2“) … Here’s a method I wrote a while ago:
/// <summary>
/// Constructs a QueryString (string).
/// Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"
/// </summary>
/// <param name="nvc">NameValueCollection</param>
/// <returns>String</returns>
public static String ConstructQueryString(NameValueCollection parameters)
{
List<String> items = new List<String>();
foreach (String name in parameters)
items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name])));
return String.Join("&", items.ToArray());
}
Just in case you didn’t know about the System.Web.HttpUtility.ParseQueryString method, it’s a quick way of converting a query (key/value pairs) string back into a NameValueCollection.



don’t you mean foreach(string name in parameters.Keys ) ?
Ross
6 Jun 08 at 2:58 pm
Wow I take it back, 6 years and I never noticed that you don’t need the .Keys on a NV collection.
Ross
6 Jun 08 at 3:01 pm
Fair point… and “parameters.Keys” does make more sense really.
Lee Kelleher
6 Jun 08 at 3:24 pm
Thanks for that! Nice neat method…. Been searching for an easy to use URL encoding facility in .NET.
And the icing on the cake is that I didn’t even know about the String.Join method - that’s gonna get used time and time again.
Cheers!
Chris
4 Jul 08 at 7:45 pm
Cheers Chris, glad I could help.
Lee Kelleher
7 Jul 08 at 8:48 pm