Tuesday, December 22, 2009

Programmatically Deleting versions from a Sharepoint Document library

Some programming tasks are straight forward with SharePoint API. But, some times, you gotta be tricky.
There is a trick to delete the versions from a SharePoint document library.
each time a version is deleted from the document library, item index will be changed. So, the version item collection gets flushed for each and every delete. To deal with this item Index change, we need to itereate through all the folders and files and make sure to delete the first indexed file always(file.Versions[0].Delete()). This makes sure that the lowest indexed item will be deleted for each and every index flush.


SPSite site = new SPSite("http://servername/sites/sitecollname");
SPWeb web = site.OpenWeb();  
web.AllowUnsafeUpdates = true;
SPDocumentLibrary docLib=(SPDocumentLibrary)web.Lists["Documents"];
foreach (SPListItem folder in docLib.Folders)
  {
     for (int i = 0; i < folder.Folder.Files.Count; i++)
         {

SPFile file = folder.Folder.Files[i];
int counter = file.Versions.Count;

for (int j = 0; j < counter; j++)
{
if (file.Versions[0] != null)
{
file.Versions[0].Delete();
}

}
}

}
web.Update();
web.AllowUnsafeUpdates = false;

4 comments:

  1. Hey, Umakanth :) I'm experiencing problems with that in Vista in my laptop, but the XP pc works fine. Do you know what should I do?

    ReplyDelete
  2. Is it possible to update a file in document library with a lower minor version, once it is approved?

    ReplyDelete
  3. I am new at this, so please bare with me. I need to go through a document libray with thousands of docs and thousands of versions. I need to trim them down to the newest 5 versions. So I need to delete the older versions and leave the newest 5.

    Also, isn't version "0" the current version?

    ReplyDelete