I have the following code to get the sub-folders and files inside a folder, but this code will not retrieve any sub-folder and files found at deeper level. so can anyone advice how i can get all the files and folders within a folder?

Folder folder = context.Web.GetFolderByServerRelativeUrl(context.Web.ServerRelativeUrl + "/library3/" + currentFilingSystemItem["DealName"].ToString());
FileCollection files = folder.Files;
FolderCollection folders = folder.Folders;
context.Load(files, fs => fs.Include(f => f.ListItemAllFields));
context.Load(folders, fs => fs.Include(f => f.ListItemAllFields));
foreach (File f in files)

foreach (Folder fo in folders)

2 Answers 2


Try the below logic to get all the files from a folder and it's sub folder, the below caml query has RecursiveAll which brings up all the files from a folder including all it's sub folders. Alter the below clientContext.Load with required fileds to be included.

    CamlQuery camlQuery = new CamlQuery();
    camlQuery = new CamlQuery();
    camlQuery.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                "<Query>" +
                "<Where>" +
                            "<Eq>" +
                                "<FieldRef Name=\"FileDirRef\" />" +
                                "<Value Type=\"Text\">/sites/test/list/folder1</Value>" +
                             "</Eq>" +
                "</Where>" +
                "</Query>" +
    ListItemCollection listItems = DocumentsList.GetItems(camlQuery);
    foreach (ListItem item in listItems)
  • this CAML will only return a single item not all the folders and files..
    – John John
    Feb 26, 2020 at 20:14

We can use the following code to achieve it.

Folder folder = context.Web.GetFolderByServerRelativeUrl(context.Web.ServerRelativeUrl + "/library3/" + currentFilingSystemItem["DealName"].ToString());

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = @"<View Scope='RecursiveAll'>
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = context.Web.Lists.GetByTitle("library3").GetItems(camlQuery);
foreach (ListItem oListItem in listItems)
    Console.WriteLine("Name: {0}", oListItem["FileLeafRef"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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