0

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?

  • Incidentally, I am investigating this as a possible workaround for a problem described in [this thread](http://stackoverflow.com/questions/5267020/datapager-controls-use-sitecore-layout-url-instead-of-item-url). –  Mar 11 '11 at 17:35

2 Answers2

2

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");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks, that did it! I ended up having to use uriBuilder.Uri.PathAndQuery instead of uriBuilder.ToString() though. See [this thread](http://stackoverflow.com/questions/5267020/datapager-controls-use-sitecore-layout-url-instead-of-item-url/5304861#5304861) for more info. –  Mar 14 '11 at 22:28
0

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

skaz
  • 21,962
  • 20
  • 69
  • 98