Search code examples
sharepointsharepoint-onlinesharepoint-rest-api

Is there a Sharepoint API to get nested directory structure for a particular folder at once within a site?


Is there a Sharepoint API to get entire content of files/folders for a particular folder at once ? I don't want to use GetFolderByServerRelativePath recursively.


Solution

  • If don't want to use GetFolderByServerRelativePath, you can use CSOM with CAML Query like this:

                string password = "pwd";
                string account = "user@Tenant.onmicrosoft.com";
                var secret = new SecureString();
                foreach (char c in password)
                {
                    secret.AppendChar(c);
                }
                using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename"))
                {
                    ctx.Credentials = new SharePointOnlineCredentials(account,secret);
                    Web web = ctx.Web;
                    ctx.Load(web);
                    ctx.ExecuteQuery();
                    List list = web.Lists.GetByTitle("Documents");
                    ctx.Load(list);
                    ctx.ExecuteQuery();
                    Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/shared%20documents/");
                    ctx.Load(folder);
                    ctx.ExecuteQuery();
    
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View Scope='RecursiveAll'>
                                         <Query>
                                         </Query>
                                     </View>";
                    camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
                    ListItemCollection listItems = list.GetItems(camlQuery);
                    ctx.Load(listItems);
                    ctx.ExecuteQuery();
                    foreach (var item in listItems)
                    {
                        Console.WriteLine(item.FieldValues["FileRef"].ToString());
                    }
                }
    

    will return all folders/subfolders/files together, hopefully, this is what you need.