System.Uri - (Apparently) Poor API decisions..
Tim Marman posts: " Can anyone offer a compelling reason why the BasePath and CurrentDocument properties are (and/or should be) protected on the System.Uri object?? I can't think of one. "
I hit this very problem yesterday. Here's a quick hack to get around it. Given a url of http://weblogs.asp.net/mreynolds/default.aspx, this code breaks it down into the folder of the page, and the root folder for the server. It assumes that if the last member of the collection returned by Segments contains a dot, but no slash, it's a document name.
// uri...
Uri uri = new Uri(pageUrl);
string rootFolder = uri.AbsoluteUri.Substring(0, uri.AbsoluteUri.Length - uri.LocalPath.Length) + "/";
// is the last segment a bit suspect? does it contain no slash, but has a dot?
string last = uri.Segments[uri.Segments.Length - 1];
int lastIndex = uri.Segments.Length - 1;
if(last.IndexOf("/") == -1 && last.IndexOf(".") != -1)
lastIndex--;
else
{
if(pageUrl.EndsWith("/") == false)
pageUrl = pageUrl + "/";
}
// builder...
StringBuilder builder = new StringBuilder();
builder.Append(rootFolder);
for(int i = 0; i <= lastIndex; i++)
builder.Append(uri.Segments[i]);
string pageFolder = builder.ToString();
The results:
pageUrl: http://weblogs.asp.net/mreynolds/default.aspx
pageFolder: http://weblogs.asp.net/mreynolds/
rootFolter: http://weblogs.asp.net/