Modifying just the path part of a Hyperlink's NavigateUrl in C#

…衆ロ難τιáo~ 提交于 2019-12-24 21:10:03

问题


I would like to modify the NavigateUrl property of a Hyperlink control. I need to preserve the querystring but change the path of the hyperlink's URL.

Something along these lines:

var control = (Hyperlink) somecontrol;

// e.g., control.NavigateUrl == "http://www.example.com/path/to/file?query=xyz"

var uri = new Uri(control.NavigateUrl);
uri.AbsolutePath = "/new/absolute/path";

control.NavigateUrl = uri.ToString();

// control.NavigateUrl == "http://www.example.com/new/absolute/path?query=xyz"

Uri.AbsolutePath is read-only (no setter defined), though, so this solution won't work.

How would I change just the path of a Hyperlink's NavigateUrl property while leaving the querystring, hostname and schema parts intact?


回答1:


You may find the UriBuilder class useful:

var oldUrl = "http://www.example.com/path/to/file?query=xyz";
var uriBuilder = new UriBuilder(oldUrl);
uriBuilder.Path = "new/absolute/path";
var newUrl = uriBuilder.ToString();

or to make it a little more generic:

public string ChangePath(string url, string newPath)
{
    var uriBuilder = new UriBuilder(url);
    uriBuilder.Path = newPath;
    return uriBuilder.ToString();
}

and then:

var control = (Hyperlink) somecontrol;
control.NavigateUrl = ChangePath(control.NavigateUrl, "new/absolute/path");



回答2:


You could split the String at the first question mark and then concatenate the new domain with that.



来源:https://stackoverflow.com/questions/5276324/modifying-just-the-path-part-of-a-hyperlinks-navigateurl-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!