Reverse function of HttpUtility.ParseQueryString

Palani picture Palani · Apr 9, 2010 · Viewed 7.2k times · Source

.Net's System.Web.HttpUtility class defines the following function to parse a query string into a NameValueCollection:

public static NameValueCollection ParseQueryString(string query);

Is there any function to do the reverse (i.e. to convert a NameValueCollection into a query string)?

Answer

Ivan Hamilton picture Ivan Hamilton · Dec 22, 2011

System.Collections.Specialized.NameValueCollection does NOT support this, but a derived internal class System.Web.HttpValueCollection DOES (by overriding ToString()).

Unfortunately (being internal) you cannot instantiate this class directly, but one is returned by HttpUtility.ParseQueryString() (and you can call this with String.Empty, but not Null).

Once you have a HttpValueCollection, you can fill it from your original NameValueCollection by calling Add(), before finally calling ToString().

var nameValueCollection = new NameValueCollection {{"a","b"},{"c","d"}};
var httpValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
var qs = httpValueCollection.ToString();

nameValueCollection.ToString() = "System.Collections.Specialized.NameValueCollection" httpValueCollection.ToString() = "a=b&c=d"