Delete SharePoint item versions programmatically in SharePoint

Lets see how to get all version associated with a document.

SPSite oSite = new SPSite("URL");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["Documents"];
foreach (SPListItem doc in oList.Items)
SPListItemVersionCollection coll = doc.Versions;
foreach (SPListItemVersion version in coll)
Console.Writeline('VersionLabel: ' + version.VersionLabel + ' IsCurrentVersion: ' + version.IsCurrentVersion )
In the above way you can get all version of a document in sharepoint object Model. If you wanna programatically remove all the version , then better make use of SPFileVersionCollection, Since it is going to remove/delete all version except the Current version .
foreach (SPListItem doc in documentLibrary.Items)
SPFileVersionCollection coll = doc.File.Versions;
foreach (SPFileVersion version in coll)
//Either use Recycle() or Delete()

But the best way for delete versions are usage of VersionCollection.


debasish mishra said...

Can I move only the versions to recycle bin through code.

Post a Comment

Popular Posts