2

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)
    {
    }
1

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>" +
                "</View>";
    ListItemCollection listItems = DocumentsList.GetItems(camlQuery);
    clientContext.Load(listItems);
    clientContext.ExecuteQuery();
    foreach (ListItem item in listItems)
    {
       console.writeline(item["Title"]); 
    }```
| improve this answer | |
  • this CAML will only return a single item not all the folders and files.. – SharePoint TestDev Feb 26 at 20:14
1

We can use the following code to achieve it.

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

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

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.