DriverBoy DriverBoy - 4 years ago 120
C# Question

Append values to query string

I have set of URL's similar to the ones below in a list

I have managed to get the query strings using the following code:

myurl = longurl.Split('?');
NameValueCollection qs = HttpUtility.ParseQueryString(myurl [1]);

foreach (string lol in qs)
// results will return

But it only returns the parameters like
id, server, location and so on based on the URL provided.

What I need is to add / append values to the existing query strings.

For example with the URL:

I need to alter the values of the query string parameters:



As you can see, I have appended "1" for each value. I need to get a set of URL's from a string with different query strings in them and add a value to each parameter at the end & again add them to a list.

Answer Source

You could use the HttpUtility.ParseQueryString method and an UriBuilder which provides a nice way to work with query string parameters without worrying about things like parsing, url encoding, ...:

string longurl = "";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["action"] = "login1";
query["attempts"] = "11";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
// ""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download