Connor Ferguson
Connor Ferguson

Reputation: 67

SharePoint CSOM API CAML Query to get all sub folder names of root folder paginated

I am trying to do something fairly simple with the SharePoint CSOM API. I have a library which has over 5000 folders in on the root level, i need to read the names of all of those subfolders as efficiently as possible but cant find a simple solution. Below is what i have so far, the idea being that i do a query to find items on the library level then filter out on the object type but i get the 'The attempted operation is prohibited because it exceeds the list view threshold.' error message. How do i achieve this?

Function GetPaginatedFirstLevelSubFolders(context As ClientContext, listName As String) As List(Of String)

Dim allSubFolders As New List(Of String)()
Dim list As List = ctx.Web.Lists.GetByTitle(listName)
ctx.Load(list.RootFolder)
ctx.ExecuteQuery()
Dim libraryRootFolderUrl As String = list.RootFolder.ServerRelativeUrl
Dim position As ListItemCollectionPosition = Nothing

Do
    Dim camlQuery As CamlQuery = New CamlQuery()
    camlQuery.ListItemCollectionPosition = position
    camlQuery.FolderServerRelativeUrl = libraryRootFolderUrl
    camlQuery.ViewXml = $"<View Scope='Recursive'>
                        <Query>
                        <Where>
                        <Eq><FieldRef Name=""FileDirRef"" />
                        <Value Type=""Text"">" & libraryRootFolderUrl + "</Value>
                        </Eq>
                        </Where>
                        <RowLimit Paged='TRUE'>5000</RowLimit>
                        </Query>
                        </View>"

    Dim listItems As ListItemCollection = list.GetItems(camlQuery)
    context.Load(listItems)
    context.ExecuteQuery()
    position = listItems.ListItemCollectionPosition

    For Each item As ListItem In listItems
        If item.FileSystemObjectType = FileSystemObjectType.Folder Then
            Dim folderPath As String = item("FileRef")
            If IO.Path.GetDirectoryName(folderPath) = libraryRootFolderUrl Then
                allSubFolders.Add(IO.Path.GetFileName(folderPath))
            End If
        End If
    Next

Loop While position IsNot Nothing

Return allSubFolders

End Function

Upvotes: 0

Views: 31

Answers (0)

Related Questions