2

I have a SharePoint Library and I want to traverse all folders, sub folders and files of it using client object model. How can this be done?

9

you can use the below code to traverse a specified document library using client object model.

using Microsoft.SharePoint.Client;

class Program
    {
        static void Main()
        {
            using (ClientContext clientContext = new ClientContext("Your Site URL "))
            {
                List docList = clientContext.Web.Lists.GetByTitle("Document Library Name");
                clientContext.Load(docList); CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View Scope='RecursiveAll'></View>";
                ListItemCollection listItems = docList.GetItems(camlQuery);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
                foreach (ListItem listItem in listItems)
                Console.WriteLine("Id: {0} ", listItem.Id);
            }
            Console.ReadLine();
        }
    }

The above code will traverse the specified document library's folders, Sub Folders and prints the item ID's. Before executing the code, please add reference to the following DLL's

1. Microsoft.SharePoint.Client.dll 
2. Microsoft.SharePoint.Client.Runtime.dll 

To display the folder and subfolder names and the item names inside the folder nd subfolder, use the below code

using (ClientContext ctx = new ClientContext("Your site name"))
            {
                Web web = ctx.Web;
                ctx.Load(web);
                Microsoft.SharePoint.Client.List docList = web.Lists.GetByTitle("Document library Name");
                ctx.Load(docList);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View Scope='RecursiveAll'></View>";
                ListItemCollection listCol = docList.GetItems(camlQuery);
                ctx.Load(listCol);
                ctx.ExecuteQuery();
                foreach (Microsoft.SharePoint.Client.ListItem item in listCol)
                {
                    Console.WriteLine("FileDirRef: {0}", item["FileDirRef"]);
                    Console.WriteLine("FileLeafRef: {0}", item["FileLeafRef"]);
                    Console.WriteLine();
                }
                Console.ReadKey();
            }
  • Hi Sakthi, Now I have altered the code and tested. Its traversing all the folders and subfloders in a Library. Hope it might help you. – Karthik Jaganathan Jun 21 '13 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.