sharepointcsomsharepoint-clientobject

SharePoint Online: Get Document Library Children Count Using CSOM


My requirement is to get the children item count of Document Library using CSOM. The count should only be the immediate children count, and should not include the sub-children count. I am trying to use below code to achieve this:

var newObjClientContext = this.GetSharePointClientContext(accessToken, fullUri);
WebCollection collWeb = newObjClientContext.Web.GetSubwebsForCurrentUser(new SubwebQuery());
var documentLibrary = newObjClientContext.Web.Lists.GetById(docID);

ListItemCollection ltitems = null;

string vquery = @"<View >
                <Query>
                    <Where> 
                        <Or> 
                            <Eq>
                                <FieldRef Name='FSObjType' /> 
                                <Value Type='Lookup'>1</Value>
                            </Eq> 
                            <Eq>
                                <FieldRef Name='FSObjType' /> 
                                <Value Type='Lookup'>0</Value>
                            </Eq> 
                            </Or> 
                        </Where>
                        <OrderBy><FieldRef Name='FileLeafRef' Ascending='TRUE'></FieldRef></OrderBy>                                        
                    </Query>
                    <RowLimit>" + recCount + @"</RowLimit>
                    </View>";

CamlQuery camlQuery = new CamlQuery();

camlQuery.ViewXml = vquery;
ltitems = documentLibrary.GetItems(camlQuery);
newObjClientContext.Load(documentLibrary);
newObjClientContext.Load(ltitems, lists => lists.IncludeWithDefaultProperties(l => l.ParentList));

newObjClientContext.ExecuteQuery();

int totalcount = documentLibrary.ItemCount; //It includes count of all the items present at all levels.

Can anyone suggest how can I get children count in above step?


Solution

  • If I have interpreted your requirement correctly you want the root level child item count of the document library? This is easily achieved using the ItemCount property of document libraries RootFolder.

    var list = web.Lists.GetByTitle("Documents");
    cc.Load(list.RootFolder, l => l.ItemCount);
    cc.ExecuteQuery();
    
    var rootChildItemCount = list.RootFolder.ItemCount;
    

    Or do you require the child item count of every folder in your document library? This can be achieved with a CamlQuery. Let me know if your require a solution for this.