100

What is the nicest way of replacing the host-part of an Uri using .NET?

I.e.:

string ReplaceHost(string original, string newHostName);
//...
string s = ReplaceHost("http://oldhostname/index.html", "newhostname");
Assert.AreEqual("http://newhostname/index.html", s);
//...
string s = ReplaceHost("http://user:pass@oldhostname/index.html", "newhostname");
Assert.AreEqual("http://user:pass@newhostname/index.html", s);
//...
string s = ReplaceHost("ftp://user:pass@oldhostname", "newhostname");
Assert.AreEqual("ftp://user:pass@newhostname", s);
//etc.

System.Uri does not seem to help much.

svick
  • 236,525
  • 50
  • 385
  • 514
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189

2 Answers2

170

System.UriBuilder is what you are after...

string ReplaceHost(string original, string newHostName) {
    var builder = new UriBuilder(original);
    builder.Host = newHostName;
    return builder.Uri.ToString();
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Ishmael
  • 30,970
  • 4
  • 37
  • 49
44

As @Ishmael says, you can use System.UriBuilder. Here's an example:

// the URI for which you want to change the host name
var oldUri = Request.Url;

// create a new UriBuilder, which copies all fragments of the source URI
var newUriBuilder = new UriBuilder(oldUri);

// set the new host (you can set other properties too)
newUriBuilder.Host = "newhost.com";

// get a Uri instance from the UriBuilder
var newUri = newUriBuilder.Uri;
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 3
    I suspect it might be better to obtain the `Uri` instance by calling `newUriBuilder.Uri` rather than formatting and parsing it. – Sam Jun 13 '13 at 02:35
  • @Sam you're right, the [`Uri`](http://msdn.microsoft.com/en-us/library/system.uribuilder.uri.aspx) property is a much better option. Thanks. Updated. – Drew Noakes Jun 14 '13 at 13:38
  • Careful of the `.Uri` call. If you have something in that `UriBuilder` that does not translate to a valid Uri, it will throw. So for example if you need a wildcard host `*` you can set `.Host` to that, but if you call `.Uri` it will throw. If you call `UriBuilder.ToString()` it will return the Uri with the wildcard in place. – CubanX Jul 18 '19 at 17:25