SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My company has a document library with several levels of sub folders. I'm aware this isn't ideal, meta data would be better, etc., but this is what I have to work with. I'm looking to list out the contents of this document library in an unordered list on an ASPX page. Each sublevel would be another nested UL, under a heading which would be the folder name.

Long story short - how do I A) get subfolder names in C#, and B) get the files in those subfolders?

I'm familiar with iterating through files ala

    SPSite site = new SPSite("****");
    SPWeb web = site.OpenWeb();
    SPList list = web.Lists["docLibrary"];

    foreach (SPListItem i in list.Items)
        formList.Text += i["Name"] + "<br />";

but I don't quite know where to go from here. Thanks.

share|improve this question
up vote 0 down vote accepted

You can use below pesudocode in a recursive function to get all files and folders in a list:

foreach (SPFolder oFolder in List.RootFolder.SubFolders)
                           foreach (SPFile oFile in oFolder.Files)


share|improve this answer

The recursive approach is not a good idea IMO.

You are better off simply getting all of the objects and using the EncodedAbsUrl. Retrieve the objects using SPSiteDataQuery.

If the list size is large, consider doing it in chunks (paged) instead of retrieving the entire set at once.

Using the EncodedAbsUrl of the result is a good approach because the URL is inherently hierarchical and you can build the tree view pretty easily just by breaking the URL into the component parts.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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