98

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
  • 225,720
  • 49
  • 378
  • 501
Rasmus Faber
  • 47,301
  • 20
  • 140
  • 187

2 Answers2

165

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,073
  • 146
  • 84
  • 117
Ishmael
  • 28,389
  • 4
  • 36
  • 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
  • 284,599
  • 158
  • 653
  • 723
  • 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