Programmatically set retention policy SharePoint 2010

When it comes to applying your retention schedule to your content, you have two choices. You can attach the retention schedule to the content type or you can attach it to the list. When attached to the content type, the retention schedule will be followed regardless of where the content type is created. In this post however we will first see how to add a custom retention policy to a list using object model. Adding in content Type is later in the post.

In this post we will check to see if you have a custom list policy, using the ListHasPolicy property on the Microsoft.Office.RecordsManagement.InformationPolicy.ListPolicySettings object. This Boolean property returns whether the list has a custom policy. To set the list to use a custom policy, set the UseListPolicy Boolean to True and then call Update on your ListPolicySettings object. Set this to False to use the content type retention policy. In the below code the constructor for ListPolicySettings object takes a SPList object, which is the list you want to investigate. Lets see the code now.

SPWeb web = site.RootWeb;
SPList list = web.GetList(SharePointListURL);

Microsoft.Office.RecordsManagement.InformationPolicy.ListPolicySettings policy = new
Microsoft.Office.RecordsManagement.InformationPolicy.ListPolicySettings(list);

if (!policy.ListHasPolicy)
{
//make the list use a custom list policy
policy.UseListPolicy = true;
policy.Update();
}
//Check to see if setting was successful
MessageBox.Show("List Policy Set: " + policy.ListHasPolicy.ToString());

Adding to ContnetType –

public static void AddPolicyToContentType()
{
using(SPSite site = new SPSite("http://SPsite"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["list1"];
SPContentType ctype = list.ContentTypes["Document"];

if (Policy.CanHavePolicy(ctype))
{
PolicyCatalog pc = new PolicyCatalog(site);
var policy = (from p in pc.PolicyList.OfType() where p.Name == "expireme" select p).First();
Policy.CreatePolicy(ctype, policy);
Policy.ProcessChanges(site);

}
}
}