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:
Post a Comment