c# - 替换 Uri 中的主机

标签 c# .net uri

使用 .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/

相关文章:

coldfusion - 如果在井号# 之后,如何访问 Coldfusion 中的 URL 参数 ID?

uri - 在 URI 语法中支持 Zeroconf 的最佳方式?

c# - Entity Framework Visual Studio 2017 的 MySQL 数据源

c# - MySqlDataReader 没有读取我的查询,就好像没有返回行一样,但 PHPMyAdmin 返回具有相同查询的行

c# - Antlr4.3语法中的NoViableAltException

c# - 为什么我会收到此异常 : "he ' Microsoft. ACE.OLEDB.12。 0' provider is not registered on the local machine"?

android - 什么是 URI 和 extraHeaderParameters?

c# - 为什么当我按下按钮时我的列表会重置?

c# - 无法批量加载。文件 "csv"不存在或您没有文件访问权限 - Azure

.net - 在源代码管理中管理我的数据库