I am working on a method that needs to get all files under specified folder name with an option to include all subfolders (recursive). I currently have the following code in place which is working for parent folder files:
using (var spClientContext = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, _clientId, _clientSecret))
{
if (spClientContext != null)
{
List list = spClientContext.Web.Lists.GetByTitle("Documents");
spClientContext.Load(list);
spClientContext.Load(list.RootFolder);
spClientContext.Load(list.RootFolder.Folders);
spClientContext.ExecuteQuery();
FolderCollection fcol = list.RootFolder.Folders;
if (fcol != null)
{
foreach (Folder f in fcol)
{
if (f.Name.Equals(folderName, StringComparison.InvariantCultureIgnoreCase))
{
spClientContext.Load(f.Files,
items => items.Include(
item => item.Name,
item => item.Author,
item => item.ModifiedBy,
item => item.ListItemAllFields["Created"],
item => item.ListItemAllFields["Modified"],
item => item.ListItemAllFields["FileRef"],
item => item.Length)
);
spClientContext.ExecuteQuery();
FileCollection fileCol = f.Files;
foreach (File file in fileCol)
{
// do stuff
}
}
}
}
}
};
What's the best method to include files in all subfolders? Also curious, would it be better to use a CAML query here? I will need to eventually optimize to sort as well and not sure if that can only be achieved with CAML query? Thanks in advance!
It would actually be better to use CamlQuery there - you can specify the RecursiveAll
scope there which will automatically include all items and folders under a given location. So you might want to do something like this:
var camlQuery = CamlQuery.CreateAllItemsQuery();
var list = spClientContext.Web.Lists.GetByTitle("Documents");
var items = list.GetItems(camlQuery);
spClientContext.Load(items);
Then, for each item you can extract the file using the File
property on the item.
By the way - you don't need to load the list and the root folder. You should only load things properties of which you'll be reading, i.e. to get the list items, you only need to load the item collection, no need to load the entire list.