.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)?
I found that a combination of UriBuilder
and HttpUtility
classes meets my requirements to manipulate query parameters. The Uri
class on its own is not enough, particularly as its Query
property is read only.
var uriBuilder = new UriBuilder("http://example.com/something?param1=whatever");
var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
queryParameters.Add("param2", "whatever2");
queryParameters.Add("param3", "whatever2");
uriBuilder.Query = queryParameters.ToString();
var urlString = uriBuilder.Uri.ToString();
The above code results in the URL string: http://example.com/something?param1=whatever¶m2=whatever2¶m3=whatever2
Note that the ToString() goes via a Uri
property, otherwise the output string would have an explicit port 80 in it.
It's nice to be able to do all this using framework classes and not have to write our own code.
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"
A NameValueCollection has an automatic ToString() method that will write all your elements out as a querystring automatically.
you don't need to write your own.
var querystringCollection = HttpUtility.ParseQueryString("test=value1&test=value2");
var output = querystringCollection.ToString();
output = "test=value1&test=value2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With