SharePoint CSOM: Fixing the “Value does not fall within the expected range” Error Calling GetFolderByServerRelativeUrl

Comments 0

Share to social media

There are times when you just need to get a reference to a folder in the master page gallery of a site collection using CSOM, and that’s where I found myself the other day.  I had a SharePoint context, so I attempted to get my folder using:

var folder = clientContext.Web.GetFolderByServerRelativeUrl(
     "/_catalogs/masterpage/SomeFolder")

Unfortunately, instead of getting back a folder after executing my context, I got back an error

Value does not fall within the expected range.

Awesome.  I happened to remembered that my SharePoint context was pointing to a subsite and not the root web of the site collection, and after prodding around a bit I confirmed that when you call Web.GetFolderByServerRelativeUrl, the URL you pass to the method must be a child of the URL in the context.  In other words, you can’t get a folder reference that exists in a parent site, you have to get a folder that is a child of the Web instance.  Since I needed to get something in the root web of the site collection the fix was fairly easy:

var folder = clientContext.Site.RootWeb.GetFolderByServerRelativeUrl(
     "/_catalogs/masterpage/SomeFolder")

You just need to get an appropriate Web instance from which to make the call and then it should work fine.