Pages

Search This Blog

Monday, November 28, 2011

Get and Delete SharePoint List item version programmatically

When you upload a file for the very first time the version 1.0 is created, and from there you can start check in/out documents. Using versioning, you can see your document/item history and access to a particular version, and and restore it.

How to get all version associated with a document?

SPSite oSite = new SPSite("Site URL");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["Shared 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()
item.Recycle();  
 //or
 item.Delete();
}
}


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

No comments:

Post a Comment