修改超链接的NavigateUrl在C#中只是路径的一部分路径、超链接、NavigateUrl

由网友(每天都超可爱)分享简介:我想修改超链接控制 NavigateUrl 属性。我需要preserve查询字符串,但更改超链接的URL的路径。I would like to modify the NavigateUrl property of a Hyperlink control. I need to preserve the queryst...

我想修改超链接控制 NavigateUrl 属性。我需要preserve查询字符串,但更改超链接的URL的路径。

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.

这些方针的东西:


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 为只读(的没有setter定义),虽然如此,该解决方案将无法工作。

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

我将如何改变超链接 NavigateUrl 财产的人的路,而留下的查询字符串,主机名和架构部件完好无损?

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

推荐答案

您可能会发现的 UriBuilder 类有用的:

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();
}

然后:

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

相关推荐

最新文章