0

I want to find all the subfolders of a SharePoint folder using PNP framework. My current code is like this

            using (var cxt = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientId, clientSecret))
        {
            Microsoft.SharePoint.Client.Web oWebsite = cxt.Web;
            List list = oWebsite.Lists.GetByTitle("Documents");
            cxt.Load(list.RootFolder.Folders);
            cxt.ExecuteQuery();
            FolderCollection fcol = list.RootFolder.Folders;
        };

This gives me only direct descendants. But I want to get all sub folders. How can I achieve this?

4
  • 1
    Check this & this (using RecursiveAll in CAML) . let me know if it helps you. – Ganesh Sanap Apr 30 at 6:52
  • @GaneshSanapthat helped a lot, I am getting just one error at line var allFolders = folderItems.Select(i => i.Folder).ToList(); – None Apr 30 at 7:01
  • 'ListItemCollection' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'ListItemCollection' could be found – None Apr 30 at 7:01
  • As you have all the folders in folderItems. Now you can iterate over the collection using other C# methods instead of using .Select(). – Ganesh Sanap Apr 30 at 7:11
1

Try below solutions:

Solution 1:

Use CamlQuery.CreateAllFoldersQuery method in CSOM which will retrieve all folders in document library.

Example:

public static void GetAllFolders(List list)
{
    var ctx = list.Context;
    var folderItems = list.GetItems(CamlQuery.CreateAllFoldersQuery());
    ctx.Load(folderItems, icol => icol.Include(i => i.Folder));
    ctx.ExecuteQuery();
}

Source: Get all sub-folders from a specific SharePoint 2013 library using CSOM

Solution 2:

Use CAML query like below to fetch folders from document library:

<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="FSObjType" /><Value Type="Integer">1</Value></Eq></Where></Query></View>

Source: Get all document from all folder and subfolder from document library sharepoint powershell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.