Replace host in Uri

C#.NetUri

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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();
}

Solution 2 - C#

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRasmus FaberView Question on Stackoverflow
Solution 1 - C#IshmaelView Answer on Stackoverflow
Solution 2 - C#Drew NoakesView Answer on Stackoverflow