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.

Load comments

About the author

Damon Armstrong

See Profile

Damon Armstrong is a consultant with SystemwarePS in Dallas, Texas. He is also a blogger and author of Pro ASP.NET 2.0 Website Programming and SharePoint 2013 Essentials for Developers. He specializes in the Microsoft stack with a focus on web technologies like MVC, ASP.NET, JavaScript, and SharePoint. When not staying up all night coding, he can be found watching a bunch of kids, studying Biblical topics, playing golf, or recovering from staying up all night coding.