How to convert NameValueCollection to a QueryString and visa versa

I needed a full proof way to desipher a querystring that might potentially be slightly malformed
Similarly i also needed a way to build up a querystring, potentially replacing existing values while building the string

So a malformed querystring could be

I say malformed, this isn’t strictly malformed but if you tried to split this into an array of strings you might run into errors
So to pull this into a valid collection you do the following

Then to perform operations on the collection simply do the following

Here’s how to build a querystring, including easy ability to change existing values and turn it into a valid encoded querystring in one line

The output of FinishedEncodedQueryString is


Leave a Reply

Your email address will not be published. Required fields are marked *