Get all Documents from a SharePoint List using CSOM

In this post, I am going to write C# code to list all documents in a SharePoint list and get all files from SharePoint Site using Client Object Model (CSOM).

List all documents in a SharePoint Document Library

The below C# code find and list all files in the particular document library. You can replace your own list name to get required documents.

public static void GetAllDcoumentsInaList() 
{    
    string sitrUrl = "https://SPTenant.sharepoint.com/sites/contosobeta"; 
    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"); 
        var items = list.GetItems(new CamlQuery() { ViewXml = "<View Scope="RecursiveAll"><Query><Where><IsNotNull><FieldRef Name="File_x0020_Type" /></IsNotNull></Where></Query></View>" }); 
        ctx.Load(items); 
        ctx.ExecuteQuery(); 
        foreach (var doc in items) 
        { 
            Console.WriteLine(doc["FileRef"].ToString().Split('/').LastOrDefault() + 
                " (" + doc["File_x0020_Size"].ToString() + " bytes)"); 
        } 
    } 
}

Get all documents in a SharePoint Site

To retrieve items from entire site, first, we need to fetch all the lists in a site and add condition check BaseType in list to filter only document libraries.

public static void GetAllDcoumentsInaSite() 
{ 
    string sitrUrl = "https://SPTenant.sharepoint.com/sites/contosobeta"; 
    using (var ctx = new ClientContext(sitrUrl)) 
    { 
        //ctx.Credentials = Your Credentials
        ctx.Load(ctx.Web, a => a.Lists); 
        ctx.ExecuteQuery(); 
 
        foreach (List list in ctx.Web.Lists) 
        { 
            if (list.BaseType == BaseType.DocumentLibrary) 
            { 
                Console.WriteLine("List: " + list.Title); 
                Console.WriteLine("-----------------------"); 
                var items = list.GetItems(new CamlQuery() { ViewXml = "<View Scope="RecursiveAll"><Query><Where><IsNotNull><FieldRef Name="File_x0020_Type" /></IsNotNull></Where></Query></View>" }); 
                ctx.Load(items); 
                ctx.ExecuteQuery(); 
                foreach (var doc in items) 
                { 
                    Console.WriteLine(doc["FileRef"].ToString().Split('/').LastOrDefault() + 
                " (" + doc["File_x0020_Size"].ToString() + " bytes)"); 
                } 
            } 
        } 
    } 
}

Advertisement

Leave a Comment