Thursday, February 12, 2015

How to obtain a list of documents from a SharePoint library that were created X days ago using CSOM

In case you ever need to generate a list of documents contained in a SharePoint library that were created, say, 30 days ago or earlier, here is one way that you might go about doing that using CSOM:

using (ClientContext context = new ClientContext(@"https://webApplicationName/siteName"))
{
    context.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    
    List documentsLibrary = context.Web.Lists.GetByTitle("Documents");
                    
    CamlQuery query = new CamlQuery();
    query.ViewXml = "<View><Query><Where><Leq><FieldRef Name='Created'/><Value Type='DateTime'><Today OffsetDays='-30' /></Value></Leq></Where></Query></View>";
         
    //CamlQuery query = CamlQuery.CreateAllItemsQuery();
    ListItemCollection expiringDocs = approvedDocumentsLibrary.GetItems(query);
                   
    context.Load(expiringDocs);
    context.ExecuteQuery();

    foreach (ListItem document in expiringDocs)
    {
        Console.WriteLine(string.Format("{0}", document["Title"]));
    }
}

You'll notice that the crux of the filtering operation is dependent on the XML contents contained in my CamlQuery object as follows:

<View><Query><Where><Leq><FieldRef Name='Created'/><Value Type='DateTime'><Today OffsetDays='-30' /></Value></Leq></Where></Query></View>

with the <Today> element being the key to this in order to take the current date and offsetting it by 30 days in the past.

CAML Queries always take a bit of trial and error in order to get them right so I hope this helps save you some time!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.