SharePoint: Get List of Folders and Subfolders

Scenario:

A question on MSN requested for code to populate two drop downs from a document library. “DropDown A” should contain list of all the folders at the root. If we select any folder from “DropDown A”, “DropDown B” should be populated with list of all folders in the selected folder.

Resolution:

To get the list of all the folders at root, following code will help:

using(SPSite oSite = new SPSite(“Site_URL”))

{

SPWeb oWeb = oSite.OpenWeb();

SPList oList = oWeb.Lists[“DocumentLibraryName”];

SPFolderCollection oFolders = oList.RootFolder.SubFolders;

foreach (SPFolder oFolder in oFolders)

{

if (!oFolder.Name.Equals(“Forms”))

{

//use oFolder.Name property to populate DropDown A

}

}

}

Once selected, following code will populate “DropDown B” with list of subfolders:

SPFolder selFolder = oList.RootFolder.SubFolders[oList.Title + “/” + “Selected Folder Name”];

SPFolderCollection selSubFolders = selFolder.SubFolders;

foreach (SPFolder selSubFolder in selSubFolders)

{

//use subFolder.Name property to populate DropDown B

}

Advertisements

7 Comments »

  1. can it use in client object model ?

    • Farhan Faiz said

      Never tried but i think you can use it. Basic idea remains same.

  2. is this piece of code is working?

    • Farhan Faiz said

      Yup. Please let me know if you need further assistance.

  3. manikanta said

    coluld you pls tell me how to get items in the folders when we select a perticular folders from the list…

    • Farhan Faiz said

      If you able to find the reference of folder, their is a property SPFolder.item which returns all the items in the folder

  4. Aditi Das said

    Hi,
    I followed this post and was able to bind al folders into the drop down list.But while I am trying to add file to a sub folder selected from drop down list,it throws error “value does not fall in the range”.

    Any solution for this?

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: