Christian Salvador
Christian Salvador

Reputation: 311

Get SharePoint List in batches c# CSOM

Can you help me getting the items of a SharePoint library (it is a library with document sets) using CSOM. The library has a lot more than 5000 items and I know SharePoint has a limit of 5000, so I am trying to get them in batches of 500. Is it possible?

clientContext.Credentials = new SharePointOnlineCredentials(username, securePassword);
List oList = clientContext.Web.Lists.GetByTitle(libraryName);
clientContext.Load(oList);
clientContext.ExecuteQuery();
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><RowLimit>500</RowLimit></View>";
ListItemCollection allDocumentSet = oList.GetItems(query);
clientContext.Load(allDocumentSet);
clientContext.ExecuteQuery();

I do not know why is not working. I get the following error.

Microsoft.SharePoint.Client.ServerException: 'The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.'

Why do I get the error if I am getting only 500 items per batch?

Also, one additional question. When should I use "ExecuteQuery" and Load function?

Thanks!

Upvotes: 1

Views: 4736

Answers (1)

Lee
Lee

Reputation: 5493

You need run ExecuteQuery to retrieve/update the data from server.

Here is my sample test code to retrieve items more than 5000.

 List lmsList = clientContext.Web.Lists.GetByTitle("LargeList");
                ListItemCollectionPosition itemPosition = null;
                while (true)
                {
                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ListItemCollectionPosition = itemPosition;
                    camlQuery.ViewXml = @"<View><RowLimit>500</RowLimit></View>";

                    ListItemCollection listItems = lmsList.GetItems(camlQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();

                    itemPosition = listItems.ListItemCollectionPosition;
                    Console.WriteLine(itemPosition);
                    //foreach (ListItem listItem in listItems)
                    //    Console.WriteLine("Item Title: {0}", listItem["Title"]);

                    if (itemPosition == null)
                        break;

                    Console.WriteLine(itemPosition.PagingInfo);                    
                }

Upvotes: 1

Related Questions