Tuesday, December 27, 2005

System.Uri.BasePath is private, oh no!

For SharePoint developers working with URL is a crucial thing. So probably many of us noticed that BasePath property of Uri class is private. Maybe it is something like property in .NET 1.0 (example in "Framework Designing Guidelines") but I don’t think so.

So, how we can solve this? Well, in a SharePoint context I think we can use segment method, because in SharePoint we always get a file name at the end of the URL.

1 Uri testUrl = new Uri(http://testUrl.com/something/list/AllItems.aspx);

2 string basePath = testUrl.AbsolutePath.Replace(testUrl.Segments[testUrl.Segments.Length - 1], "");

In more advanced method you can check is the last segment is a file, for example by doing IndexOf(”.”);
Safer version is to use static method System.IO.Path.GetDirectoryName. Using this method we only have to replace “\” with “/” since GetDirectoryName translates it to a file path. It looks like this:

1 Uri testUrl = new Uri(http://testUrl.com/something/list/AllItems.aspx);

2 string basePath = Path.GetDirectoryName(testUrl.AbsolutePath).Replace(@"\", "/");

Here is a complete console application for you to test. If you know any other ways to get BasePath, be sure to comment this post.




 



using System;

using System.IO;


class MyApp

{

    [STAThread]

    static void Main(string[] args)

    {

        Uri testUrl = new Uri("http://testUrl.com/something/list/AllItems.aspx");


        //Segments method

        Console.WriteLine("Using segments:" +

                   testUrl.AbsolutePath.Replace(testUrl.Segments[testUrl.Segments.Length - 1], ""));


        //Path.GetDirectoryName method

        Console.WriteLine("Using Path.GetDirectoryName: " +

                Path.GetDirectoryName(testUrl.AbsolutePath).Replace(@"\", "/") + "/");

        Console.ReadLine();

    }

}


No comments: