Often we're in a situation when we need to get a server relative url from absolute url.
One of the easiest ways to do that in C# is to use System.Uri object like that:
public static string GetRelativeUrl(string absoluteUrl)
{
return new Uri(absoluteUrl).AbsolutePath;
}
And that's critical for SharePoint. If you provide escaped server relative url to Site.OpenWeb (or SPSite.OpenWeb for server OM) you'll get File not found exception for CSOM and something like There is no Web named for Server Object Model.
To avoid that and still use System.Uri I would recommend to use Uri.UnescapeDataString static method:
public static string GetRelativeUrl(string absoluteUrl)
{
return Uri.UnescapeDataString(new Uri(absoluteUrl).AbsolutePath);
}
Hope that would help!
That's it for today!
Have fun!
Comments