使用 .NET 替换 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: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 似乎没什么帮助。
最佳答案
System.UriBuilder是你所追求的...
string ReplaceHost(string original, string newHostName) {
var builder = new UriBuilder(original);
builder.Host = newHostName;
return builder.Uri.ToString();
}
关于c# - 替换 Uri 中的主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/479799/