Monday, December 10, 2012

This article will briefly explain how to traverse folders in a SharePoint Document Library. We cannot use the normal SPList item approach as folders are not recognized as items. 

Instead we need to use SPFolder approach by first getting the root folder of the list and then performing the required traversing and operations.



Required Namespaces :

System
System.IO
Microsoft.SharePoint
Microsoft.SharePoint.Administration
        


// In this we first get the list (document library and then get its root folder. This is then passed to function (recursive), which performs the operation.

       foreach (SPList list in site.Lists)
           {

               if ((list.GetType().ToString() == "Microsoft.SharePoint.SPDocumentLibrary") && !list.Hidden)
               {
                  
                   traverseFolder(list.RootFolder, siteDir.ToString());

               }
           }

// Traverse function that checks for nested folders. If yes, calls the traverse method again. If no, then perfroms the desired operations.
  
    static void traverseFolder(SPFolder fold, string path)
        {

                if ((fold.Item!=null)||(fold.Name!="FormServerTemplates"))
                {

                   //Code For Root Folder

                    foreach (SPFolder subFold in fold.SubFolders)
                    {
                        if (!(subFold.Item==null))
                            traverseFolder(subFold, listDir);
                    }

                    foreach (SPFile file in fold.Files)
                    {
                       
                      // Code to operate on files in folder

                       
                    }