SharePoint CAML Query to Get the Last Modified Child Item in a Folder

152 Views Asked by At

I created this extension method to execute a CAML query against a SharePoint IFolder to get the last modified date of any child item in a given folder path. The goal is to see if activity in the folder has gone dormant so I need to find the latest modified date of any child item in the given folder path. I would be interested if there is a better or more efficient way to get this information?

This query should return one result but I get a throttle exception about the view containing too many items:

public static async Task<DateTime?> GetLastModifiedChildItemDateAsync(this IFolder folder)
{
    IList? list = await folder.PnPContext.Web.Lists.GetByServerRelativeUrlAsync(folder.ServerRelativeUrl,
        p => p.LastItemUserModifiedDate,
        p => p.Fields.QueryProperties(p => p.InternalName, p => p.FieldTypeKind, p => p.TypeAsString,
            p => p.Title));
    
    string viewXml = $@"
              <View Scope='RecursiveAll'>
            <ViewFields>
                <FieldRef Name='Title' />
                      <FieldRef Name='FileLeafRef' />
                      <FieldRef Name='FileRef' />
                      <FieldRef Name='FileDirRef' />
                      <FieldRef Name='ParentList' />
                      <FieldRef Name='FSObjType' />
                <FieldRef Name='Created' />
                <FieldRef Name='Modified' />
                  </ViewFields>
          <Query>
            <Where>
              <Eq>
                <FieldRef Name='FileDirRef' />
                <Value Type='Lookup'>{folder.ServerRelativeUrl}</Value>
              </Eq>
            </Where>
            <OrderBy>
              <FieldRef Name='Modified' Ascending='False' />
            </OrderBy>
          </Query>
          <RowLimit>1</RowLimit>
        </View>";
    
    await list.LoadItemsByCamlQueryAsync(new CamlQueryOptions()
    {
        ViewXml = viewXml
    });
    
    IListItem? latestItem = list.Items.AsRequested().FirstOrDefault();
    DateTime lastModifiedDate = folder.TimeLastModified;

    if (latestItem != null)
    {
        bool isFolder = await latestItem.IsFolderAsync();
        lastModifiedDate = isFolder ? latestItem.Folder.TimeLastModified : latestItem.File.TimeLastModified;
    }

    return lastModifiedDate;
}
0

There are 0 best solutions below