2009-01-26 56 views
67

使用.NET取代Uri主機部分的最好方法是什麼?取代Uri中的主機

即:

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:[email protected]/index.html", "newhostname"); 
Assert.AreEqual("http://user:[email protected]/index.html", s); 
//... 
string s = ReplaceHost("ftp://user:[email protected]", "newhostname"); 
Assert.AreEqual("ftp://user:[email protected]", s); 
//etc. 

的System.Uri似乎並沒有多大幫助。

回答

103

System.UriBuilder是你所追求的......

string ReplaceHost(string original, string newHostName) { 
    var builder = new UriBuilder(original); 
    builder.Host = newHostName; 
    return builder.Uri.ToString(); 
} 
+0

謝謝,這正是我正在尋找。 – 2009-01-26 13:42:23

+0

我會推薦Uri類的,但我會錯的。好答案。 – 2009-01-26 14:43:02

41

由於@Ishmael說,你可以使用System.UriBuilder。這裏有一個例子:

// 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;