Friday, 8 January 2016

Error: Value does not fall within expected range SharePoint

While accessing SharePoint Document Library files I face a strange error as the code I was using was used before and was working fine earlier. Here was the error message:

Error: Value does not fall within expected range

Code Sample:

SPFileCollection files = currentlist.RootFolder.SubFolders[curfileitem.Url.Substring(0, curfileitem.Url.LastIndexOf('/'))].Files;

I found that if I have hierarchy of folder then the above code will throw an error.                        

Solution:

Through google I found out a new method to get files collection. Here is the code sample:

SPFolder folder = properties.Web.GetFolder(curfileitem.Url.Substring(0, curfileitem.Url.LastIndexOf('/')));

SPFileCollection files = folder.Files;

Make sure you provide full path of your folder. i.e. your web path / doc library title / folder path.