Add Retention Label And Retention Start Date To SharePoint Document Using CSOM

In this blog, you will see how to add a retention label and retention start date to SharePoint documents using CSOM.
 
I have created retentions labels for SharePoint and I want to apply the label to a specific document using CSOM. Also, I have a date time field named Closed Date and I want this date to be the retention label applied date. As we were doing migration, these dates were past dates and I need to apply these dates to the document.
 
We will see how to achieve this using CSOM in Console Application.
 
Code Snippet
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.SharePoint.Client;  
  7. using System.Net;  
  8. using System.Security;  
  9.   
  10. namespace ConsoleApp  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             // Initialize and set variables  
  17.             string siteURL = "https://m3652044.sharepoint.com/sites/VJDemo";  
  18.             string password = "84587@1234";  
  19.             string emailAddress = "[email protected]";  
  20.             string docLibName = "Documents";  
  21.             string labelName = "Confidential";  
  22.             int itemID = 2;  
  23.   
  24.             // Get the client context  
  25.             ClientContext ctx = new ClientContext(siteURL);  
  26.             SecureString securePwd = new SecureString();  
  27.             foreach (var cc in password)  
  28.             {  
  29.                 securePwd.AppendChar(cc);  
  30.             }  
  31.             ctx.Credentials = new SharePointOnlineCredentials(emailAddress, securePwd);  
  32.   
  33.             // Get the document  
  34.             ListItem item = ctx.Web.Lists.GetByTitle(docLibName).GetItemById(itemID);  
  35.             ctx.Load(item);  
  36.             ctx.ExecuteQuery();  
  37.   
  38.             // Get the datetime field value  
  39.             // Set retention label and date  
  40.             DateTime closedDateTime = Convert.ToDateTime(item.FieldValues["ClosedDate"]);  
  41.             item.SetComplianceTagWithMetaInfo(labelName, falsefalse, closedDateTime, emailAddress, false);  
  42.             item.Update();  
  43.             ctx.ExecuteQuery();  
  44.   
  45.             // Display the label name  
  46.             Console.WriteLine(item.FieldValues["_ComplianceTag"]);  
  47.             Console.ReadLine();  
  48.         }  
  49.     }  
  50. }  
Result
 
Add Retention Label And Retention Start Date To SharePoint Document Using CSOM 
 

Summary

 
In this blog, you saw how to add a retention label and retention start date to SharePoint documents using CSOM.