0

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 URL 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 URL back in a string with those new parameters. What is the proper way to do it? Something like getting the URL without patterns from my original string and merging the obtained parameters?

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

How I do is simple. From my original URL I substring up to the "?", then I combine with qs.ToString()

Cher
  • 2,789
  • 10
  • 37
  • 64

1 Answers1

1

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;
Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
  • thanks!! I prefer it than me method. Too bad there isn't a class that does it all... I think that replacing parameter from a URL is common stuff... – Cher Aug 14 '16 at 23:06
  • 1
    Yes, it is, but I suppose that they chose not do duplicate the functionality of `string.Join()` and `KeyValuePair.ToString()`. You could add a trivial extension method to `Uri` to do it for you. – Paul Hicks Aug 14 '16 at 23:10
  • 1
    I've just been browsing through the solutions in [this popular question](http://stackoverflow.com/q/829080/3195526). I can only assume that `UrlBuilder` did not exist at the time those answers were written. In particular, the comments on the question suggest that it didn't exist in 2013. – Paul Hicks Aug 14 '16 at 23:24