Cher Cher - 1 year ago 61
C# Question

How to properly change URL parameters?

First let me explain what I mean by properly: I found many methods out there, but most of them will end up using string manipulations and things like that. I'd like to know if there is a simple way to do such using built in functions.

So far I change the parameters of a

with a
string myNewValue

Uri myUri = new Uri(URL);
var qs = HttpUtility.ParseQueryString(myUri.Query);
qs["ParameterName"] = myNewValue;

This does work pretty well. Now I'd like to get my
back in a
with those new parameters. What is the proper way to do it? Something like getting the
without patterns from my original string and merging the obtained parameters?

Note: So far I'm able to do it with
and such, I just find it "unclean" when one start to find chars in a string to
stuff from it.

How I do is simple. From my original URL I substring up to the "
", then I combine with

Answer Source

Does the UriBuilder class offer enough power to you? It doesn't do everything (in particular, it doesn't build paths) but the missing bits are easy to fill in. For example, the default ToString of KeyValuePair<string, string> works well with string.Join():

var myUri = new Uri(url);
var qs = HttpUtility.ParseQueryString(myUri.Query);
qs["param1"] = "newVal1";

var path = string.Join("&", qs); // UriBuilder can't do this bit for you
// But it can put the bits back together and look after oddities,
// slashes, url encoding, etc.
var builder = new UriBuilder(myUri) {Path = path};
var newUri = builder.Uri;

For extra tidiness in your code, this could be wrapped up in an extension method like this:

public static Uri SetAttribute(this Uri uri, string key, string value) {
  var qs = HttpUtility.ParseQueryString(uri.Query);
  qs[key] = value;
  return new UriBuilder(myUri) {Path = string.Join("&", qs)}.Uri;

Now the original code becomes:

Uri myUri = new Uri(URL);
myUri.SetAttribute("ParameterName") = myNewValue;