4

I am trying to get the count of the number of items in a SPFolder. I have tried several things so far however they seem to break once I add two subfolders. I want the total number of files in all folders contained within the top level folder (excluding folders as part of the total).

Example Folder Structure:

-Business Plans - 4 Files

--Archives - 1 File

---2012 - 1 File

What I have Tried (fldr = BusinessPlans in these scenarios):

    //Example A:
    SPQuery query = new SPQuery();
    query.Folder = fldr;
    SPListItemCollection allitems = list.GetItems(query);
    int filecount = allitems.Count;

    //Example B:
    int filecount = fldr.Files.Count;

    //Example C:
    int filecount = fldr.ItemCount;

All seem to return filecount = 5

Any idea what I am doing wrong here or do I have to write a recursive function that total all the files up?

6

I added the recursive scope to the query and had success:

SPQuery query = new SPQuery();
query.Folder = fldr;

//Recursive Scope....
query.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection allitems = list.GetItems(query);
int filecount = allitems.Count;

Are there any better solutions?

1

try using SPFolder.ItemCount

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfolder.itemcount(v=office.14).aspx

   using(SPSite site = new SPSite("site url"))
    {
      using(SPWeb web = site.OpenWeb())
      {
        SPFolder folder = web.GetFolder("/Docs/folder1");
        int count = folder.ItemCount;
      }
    }
  • 2
    If I am not mistaken this only worked for 1 subfolder, not multiple... – BlueBird Apr 10 '13 at 17:38

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.