Friday, April 27, 2012

How to get the list of all unique folder within a sharepoint 2007 list.

As we know in SharePoint lists we can store data in the forms of folders. If you want to get the list of the names of all unique folders. This method can be pretty useful for us it will return us the list collection of all unique folders.

public List<string> GetFolderNames(SPWeb objSPWeb)
        {
            List<string> FolderNames = new List<string>();
            SPList objSPList = objSPWeb.Lists["DemoListName"];
            SPQuery objSPQuery = new SPQuery();
            objSPQuery.ViewAttributes = "Scope ='Recursive'";
            objSPQuery.Query = "";
            SPListItemCollection objSPListCol = objSPListUserOfferings.GetItems(objSPQuery);
            if (objSPListCol != null && objSPListCol.Count > 0)
            {
                foreach (SPListItem item in objSPListCol)
                {
                    SPFile f = item.Web.GetFile(item.Url);
                    if (!FolderNames.Contains(f.ParentFolder.Name))
                    {
                       FolderNames.Add(f.ParentFolder.Name);
                    }
                }
            }
            return FolderNames;
        }
    }