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. namespace ConsoleApp
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. // Initialize and set variables
  16. string siteURL = "https://m3652044.sharepoint.com/sites/VJDemo";
  17. string password = "84587@1234";
  18. string emailAddress = "[email protected]";
  19. string docLibName = "Documents";
  20. string labelName = "Confidential";
  21. int itemID = 2;
  22. // Get the client context
  23. ClientContext ctx = new ClientContext(siteURL);
  24. SecureString securePwd = new SecureString();
  25. foreach (var cc in password)
  26. {
  27. securePwd.AppendChar(cc);
  28. }
  29. ctx.Credentials = new SharePointOnlineCredentials(emailAddress, securePwd);
  30. // Get the document
  31. ListItem item = ctx.Web.Lists.GetByTitle(docLibName).GetItemById(itemID);
  32. ctx.Load(item);
  33. ctx.ExecuteQuery();
  34. // Get the datetime field value
  35. // Set retention label and date
  36. DateTime closedDateTime = Convert.ToDateTime(item.FieldValues["ClosedDate"]);
  37. item.SetComplianceTagWithMetaInfo(labelName, false, false, closedDateTime, emailAddress, false);
  38. item.Update();
  39. ctx.ExecuteQuery();
  40. // Display the label name
  41. Console.WriteLine(item.FieldValues["_ComplianceTag"]);
  42. Console.ReadLine();
  43. }
  44. }
  45. }
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.