Search code examples
c#parametersquery-string

Append values to query string


I have set of URLs similar to the ones below in a list

  • http://somesite.example/backup/lol.php?id=1&server=4&location=us
  • http://somesite.example/news.php?article=1&lang=en

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:

http://somesite.example/backup/index.php?action=login&attempts=1

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

action=login1

attempts=11

As you can see, I have appended "1" for each value. I need to get a set of URLs 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.


Solution

  • 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 = "http://somesite.example/news.php?article=1&lang=en";
    var uriBuilder = new UriBuilder(longurl);
    var query = HttpUtility.ParseQueryString(uriBuilder.Query);
    query["action"] = "login1";
    query["attempts"] = "11";
    uriBuilder.Query = query.ToString();
    longurl = uriBuilder.ToString();
    // "http://somesite.example:80/news.php?article=1&lang=en&action=login1&attempts=11"