I have a list that contains folders.

Using c# and object model, how can I see if the folder contains any items, or return a collection of all the items in that folder.

  • Cant this above functionality done by using the services offered by sharepoint? – user15740 Mar 20 '13 at 5:14

Try the following code to get the items based on the folder,

using(SPSite site = new SPSite("site url"))
  using(SPWeb web = site.OpenWeb())
    SPFolder folder = web.GetFolder("/Docs/folder1");
    if(folder.ItemCount > 0)
      SPList list = web.Lists.TryGetList("ListName");
      SPQuery query = new SPQuery();
      query.Folder = folder;
      SPListItemCollection listitem = list.GetItems(query);
  • 1
    Copycat :) But nothing really wrong because you tried to provided code example. I really hope that SPListItemCollection = list.GetItems(query); is typing error? And using TryGetList is meaningless because you don't check later if list != null. So if list doesn't exist your code will throw exception - same if you used web.Lists["ListName"]. – Vedran Rasol Sep 21 '11 at 13:17

You need to use SPQuery Class and define SPQuery.Folder Property

  • 1
    @soniiic when you down vote somebody it is polite to leave a comment – Vedran Rasol Sep 22 '11 at 21:32
foreach (SPFolder folder in list.Folders) {
    if (folder.ItemCount > 0) {
        foreach (SPFile file in folder.Files) {
            SPListItem item = file.Item;
            // Do stuff with your item here.
        foreach (SPFolder subfolder in folder.SubFolders) {
            // Do stuff with your folder here.
            // Think about perhaps using recursion if you want to list the items from this folder and beyond

Because we're using foreach, we don't really need to check if the itemcount is more than 0. But this is just an example to allow you to identify which folders have items and how you can access them

  • 1
    -1 - Right now I am working on one medium size library with ~15k documents in ~2k folders (2 levels deep) with size of few Gb. Running this code against it would be suicide. Using SPFile is also wrong if you don't want to change content of file. @soniiic please read Best Practices: Common Coding Issues When Using the SharePoint Object Model – Vedran Rasol Sep 21 '11 at 11:16
  • 1
    It doesn't matter if you have 15k or just one item, bad coding practices are always bad. Instead of whining you should learn to accept criticism. And after reading your comment I don't have any doubts about my down vote. – Vedran Rasol Sep 21 '11 at 19:15

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.