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/

 

6 Comments

  • Nice. Maybe I'll use that code instead. My current workaround was to derive from System.Uri and expose those properties under different names... which might not be &quot;safe&quot;, plus I have to use a custom Uri object.





    But that still doesn't answer the question as to why it's protected in the first place.

  • Yeah - I'd like to know why it's protected too! :-)

  • Actually, my workaround doesn't totally work, because they're not protected even - they're private! Argh. How frustrating.





    It's a good thing I can access private methods and properties through reflection :)

  • A much neater way to achive is using the build in static methods of the Path class in the System.IO Namespace.





    Code Example in C#





    Page URL: Uri.ToString();


    Page Folder: Path.GetDirectoryName(Uri.ToString();


    For Root: Path.GetPathRoot(Uri.ToString());





    Hope this hits the spot.





  • I like the last IO'one :-)

  • Rai you did hit the spot. Keep Up.

Comments have been disabled for this content.