user212218
user212218

Reputation:

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

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?

Upvotes: 0

Views: 792

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039160

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");

Upvotes: 2

skaz
skaz

Reputation: 22600

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

Upvotes: 0

Related Questions