Wednesday, May 27, 2009

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:



  1. /// <summary>
  2. /// Constructs a QueryString (string).
  3. /// Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"
  4. /// </summary>
  5. /// <param name="nvc">NameValueCollection</param>
  6. /// <returns>String</returns>
  7. public static String ConstructQueryString(NameValueCollection parameters)
  8. {
  9. List<String> items = new List<String>();

  10. foreach (String name in parameters)
  11. items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name])));

  12. return String.Join("&", items.ToArray());
  13. }

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.

From : http://blog.leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/