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
.