In this post, I am going to write CSOM based C# code to retrieve all files in a SharePoint library using Client-side Object Model. Using this CSOM code you can easily fetch all the files from document library even it has files more than List View Threshold limit.
The List View Threshold defines the maximum limit to retrieve a number of documents in a single request. By default this limit is set to 5000 rows, and in OneDrive for Business (ODFB) this limit is 20000. So any library with more than 5000 files will return an error (Ex: The number of items in this list exceeds the list view threshold, which is 5000 items).
By using CSOM, you can retrieve documents page by page by setting row limit, this will avoid the list view threshold error as we are querying only certain amount of rows in a single request.
Retrieve all documents from a SharePoint library which has more than 5000 items
The following C# code fetch all files from a SharePoint online library. It will get 100 rows in every page. You can change the row limit as per your wish. In CAML query, we are setting the view as <View Scope=’RecursiveAll’>, thus gets the documents from root folder and its sub folders by recursively.
public static List<ListItem> GetAllDocumentsInaLibrary() { List<ListItem> items = new List<ListItem>(); string sitrUrl = "https://spotenant.sharepoint.com/sites/yoursite"; using (var ctx = new ClientContext(sitrUrl)) { //ctx.Credentials = Your Credentials ctx.Load(ctx.Web, a => a.Lists); ctx.ExecuteQuery(); List list = ctx.Web.Lists.GetByTitle("Documents"); ListItemCollectionPosition position = null; // Page Size: 100 int rowLimit = 100; var camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View Scope='RecursiveAll'> <Query> <OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy> </Query> <ViewFields> <FieldRef Name='Title'/><FieldRef Name='Modified' /><FieldRef Name='Editor' /> </ViewFields> <RowLimit Paged='TRUE'>" + rowLimit + "</RowLimit></View>"; do { ListItemCollection listItems = null; camlQuery.ListItemCollectionPosition = position; listItems = list.GetItems(camlQuery); ctx.Load(listItems); ctx.ExecuteQuery(); position = listItems.ListItemCollectionPosition; items.AddRange(listItems.ToList()); } while (position != null); } return items; }
Can i use this code for sharepoint online
Yes, you can use it
How to get the files from specific sub-folder alone when there are n number of folders and n number of sub-folders in it?
Eg: /sites/doclib/folder1/subfolder/1/2/3
/sites/doclib/folder2/subfolder/1/2/3
I would like to retrieve a file from folder2–> subfolder–2