How to find item count in a SPFolder?

2020-04-13 16:56发布

问题:

I have a List that stores items in a folder hierarchy.

I notice that SPFolder.Files.Count is always zero.

Is there a way to find out how many list items are there in a folder?

回答1:

I presume you are looking for direct children and not descendants (like items within a sub-folder).

Do you also want to include sub-folders in the count? In which case you can use: SPFolder.ItemCount.

If you just want only the direct child listItems which are not subfolders then you can do something like the following:

using (SPSite site = new SPSite(mySPSite))
{
    SPWeb web = site.OpenWeb();
    SPList list = web.Lists[myList];
    SPFolder folderInstance = list.RootFolder.SubFolders[folderUrl];

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

    SPListItemCollection items = list.GetItems(query) ;

    Console.WriteLine(items.Count);
}

I haven't tried it. You might have to add a where clause to eliminate folders, if the query is returning that.

If you want to include all list-items, even within subfolders, set the SPQuery.ViewAttributes field as query.ViewAttributes = "Scope=\"Recursive\"";



回答2:

Did you try to get the SPListItem from the SPFolder and check the values from the SPBuiltInFieldId.ItemChildCount and SPBuiltInFieldId.FolderChildCount fields?

Something like this:

SPFolder folder = ...;
int? noOfItems = folder.Item[SPBuiltInFieldId.ItemChildCount] as int?;
int? noOfFolders = folder.Item[SPBuiltInFieldId.FolderChildCount] as int?;

See

SPBuiltInFieldId.ItemChildCount Field

SPBuiltInFieldId.FolderChildCount Field

for more info.



回答3:

From Microsoft

Using the SPList.ItemCount property is the recommended way to retrieve the number of items in a list. As a side effect of tuning this property for performance, however, the property can occasionally return unexpected results. For example, if you require the exact number of items, you should use ...

I wonder if the same applies to SPFolder.ItemCount ?



标签: sharepoint