Showing posts with label Versions. Show all posts
Showing posts with label Versions. Show all posts

Wednesday, May 15, 2013

Deleting all versions of a document present in document library except last 2 major and 1 minor versions Moss2007/Sharepoint2010

Recently i came across a requirement to develop a admin component which will delete all the versions of the document except some major and minor verisons present in a Sharepoint document library. Thought of sharing with you guys aswell.
In this post we are going to Delete all versions of a document present in document library except last 2 major and 1 minor versions
Below is the code snippet which performs the action.
You can made the variables int majorVersionsRequired and int minorVersionsRequired are as configurable depending on the versions you require.

try
{
   using (SPSite site = new SPSite("<<http://siteurl/>>"))
   {
      using (SPWeb web = site.OpenWeb())
      {
         SPList list = web.Lists["<<Doc Lib Name>>"];
         int majorVersionsRequired = 2;
         int minorVersionsRequired = 1;

         foreach (SPListItem item in list.Items)
         {
            SPListItemVersionCollection versionCol = item.Versions;
            int count = versionCol.Count;
            int tempMajorVersionsRequired = 0;
            int tempMinorVersionsRequired = 0;
            int versionSiNo = 0;
                           
            for (int i = 0; i <= count - 1; i++)
            {
               if (versionCol[i - versionSiNo].Level == SPFileLevel.Published)
               {
                  // this is a major version
                  tempMajorVersionsRequired++;
                  if (tempMajorVersionsRequired > majorVersionsRequired)
                  {
                     SPListItemVersion version = versionCol[i - versionSiNo];
                     version.Delete();
                     versionSiNo++;
                  }
               }
               else if (versionCol[i - versionSiNo].Level == SPFileLevel.Draft)
               {
                  //this is a minor version
                  tempMinorVersionsRequired++;
                  if (tempMinorVersionsRequired > minorVersionsRequired)
                  {
                     SPListItemVersion version = versionCol[i - versionSiNo];
                     version.Delete();
                     versionSiNo++;
                  }
               }
            }
          } 
      }
   }
}
catch (Exception ex)
{

}


Hope this helps...

Popular Posts