Retrieve list of file names from SharePoint subfolder exceeding 5,000 items

40 Views Asked by At

I need to get the list of files from a SharePoint subfolder that is going to exceed 5,000 items. I can find many examples but I cannot get any of them to work. They all seem to rely on knowing the libraryname and I don't know what that is (or how to find it).

The code that has worked up to the 5,000 limit was:

clientContext.Load(folder);
clientContext.Load(files);
clientContext.ExecuteQuery();

Obviously that breaks on >5,000 and from research I know I can't use folder or files.

From my extensive searching I have this...

string libraryName = "First Folder";
string folderUrl = "First Folder/2nd Folder/3rd Folder";
using (SP.ClientContext context = new SP.ClientContext(siteUrl))
{
    context.Credentials = new SP.SharePointOnlineCredentials(UserName, securePassword);
    SP.Web web = context.Web;
    SP.List list = context.Web.Lists.GetByTitle(libraryName);
    SP.CamlQuery camlQuery = new SP.CamlQuery();
    camlQuery.ViewXml = "<View Scope='RecursiveAll'>" +
        "<Query>" +
        "<OrderBy>" +
        "<FieldRef Name='ID' Ascending='TRUE'/>" +
        "</OrderBy>" +
        "</Query>" +
        "<RowLimit Paged='TRUE'>500</RowLimit>" +
        "</View>";
    context.Load(context.Web);
    context.ExecuteQuery();
    camlQuery.FolderServerRelativeUrl = $"{context.Web.ServerRelativeUrl}{folderUrl}";
    SP.ListItemCollectionPosition position = null

My problem is that despite playing with the folder names, it either ignores them entirely and gives me everything from Folder1 recursively (150,000+files) or it ignores the row limit in the query and crashes with a threshold error. Can someone point me in the right direction? FYI - I am a self taught hobbyist.

I found the solution although not sure if it is a fluke or intentional with the inclusion of:

<Query>
    <OrderBy Override='TRUE'>
        <FieldRef Name='FileDirRef' />
        <FieldRef Name='FileLeafRef' />
    </OrderBy>
</Query>
0

There are 0 best solutions below