0

I want to query all folders from a document library and I am using following query

<Where>
<Eq>
    <FieldRef Name="ContentType" />
    <Value Type="Text">Folder</Value>
</Eq>
</Where>

I get 2 root folders, folder 1 has a child folder and 2 files and folder 2 has no folder but 1 file, Can I get the number of child folders and files with each folder with a CAML query? for example folder 1 should give me 3 and folder 2 should give me 1 and if there is no child file or folder it should give me 0.

1

Written a console for you. You can use it as per your need

    static void Main(string[] args)
    {
        using (SPSite site = new SPSite("http://spserver:1111/"))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPList lib = web.Lists.TryGetList("TestLibrary");

                SPQuery query = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>Folder</Value></Eq></Where>";
                SPListItemCollection coll = lib.GetItems(query);
                if (coll != null && coll.Count > 0)
                {
                    foreach (SPListItem item in coll)
                    {
                        Console.WriteLine("Parent Folder : " + item.Folder.Name);
                        getChildFolder(web, item);

                    }
                }
            }
        }
    }
    static void getChildFolder(SPWeb web, SPListItem item)
    {
        SPQuery query = new SPQuery();
        query.Query = "<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>Folder</Value></Eq></Where>";
        query.Folder = item.Folder;
        SPListItemCollection coll = item.ParentList.GetItems(query);
        if (coll != null)
        {
            Console.WriteLine("\tChild Folder : " + coll.Count);
            //foreach (SPListItem folderItem in coll)
            //{
            //    Console.WriteLine("\tChild Folder : " + folderItem.Folder.Name);
            //}
        }
    }

This will give you count for each parent folder.

Folder Structure in my library:

My Library

Output:

Output

1
<View Scope="RecursiveAll">
<ViewFields>
    <FieldRef Name="FileLeafRef" />
    <FieldRef Name="FileDirRef" />
    <FieldRef Name="ItemChildCount" />
</ViewFields>
<Query>
    <Where>
        <Eq>
            <FieldRef Name="FileDirRef" />
            <Value Type="Text">/sites/devsite/Shared Documents</Value>
        </Eq>
    </Where>
</Query>
</View>

enter image description here

<FieldRef Name="ItemChildCount" /> is what I was looking for.

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.