Search code examples
sharepointrecursionsharepoint-2010sharepointdocumentlibrary

Programmatically get children of document library using recursion


I need to recurse through the contents of a document library and display them on a webpage using MVC. However I get the following error when trying to run my code: " The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."

Any help would be appreciated!

Here is my code:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DefaultModel model = new DefaultModel();


            using (ClientContext context = new ClientContext("MySPSite"))
            {
                List list = context.Web.Lists.GetByTitle("DocumentLibrary");
                Folder rootFolder = list.RootFolder;

                IEnumerable<SharePointItemBaseModel> items = ProcessFolder(rootFolder);
                model.items.AddRange(items);
            }

            return View(model);
        }

        public IEnumerable<SharePointItemBaseModel> ProcessFolder(Folder folder)
        {
            List<SharePointItemBaseModel> listItems = new List<SharePointItemBaseModel>();
            foreach (Folder childFolder in folder.Folders)
            {
                FolderModel folderModel = new FolderModel();
                IEnumerable<SharePointItemBaseModel> childFolders = ProcessFolder(childFolder,context);
                folderModel.Items.AddRange(childFolders);
                listItems.Add(folderModel);
            }

            foreach (Microsoft.SharePoint.Client.File file in folder.Files)
            {
                DocumentModel documentModel = new DocumentModel();
                documentModel.Name = file.Title;
                documentModel.modifiedBy = file.ModifiedBy.ToString();
                listItems.Add(documentModel);
            }

            return listItems;
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

Solution

  • I managed to fix this myself.

    In my recursive method I just used

    context.Load(folder.Folders);

    and

    context.Load(folder.Files);

    this initialized the collection allowing me to use it in my foreach loops