Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace host in Uri

Tags:

c#

.net

uri

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.

like image 939
Rasmus Faber Avatar asked Jan 26 '09 13:01

Rasmus Faber


2 Answers

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();
}
like image 57
Ishmael Avatar answered Nov 06 '22 01:11

Ishmael


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;
like image 44
Drew Noakes Avatar answered Nov 06 '22 01:11

Drew Noakes