1/25/2019

System.Uri and Site.OpenWeb

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;
}
One thing we should remember about this method is: System.Url automatically escapes the url. As a result, as example, https://tenant.sharepoint.com/sites/mysite/Site With Spaces will be replaced with https://tenant.sharepoint.com/sites/mysite/Site%20With%20Spaces, and AbsolutePath will return /sites/mysite/Site%20With%20Spaces.
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);
}
It will revert back the escaping.
Hope that would help!
That's it for today!
Have fun!

No comments:

Post a Comment