Programmatically delete SharePoint file versions in a Document Library

SPSite site = new SPSite(“http://yoursite/”);
SPWeb web = site.AllWebs["TestSite"];
SPDocumentLibrary mylib= (SPDocumentLibrary)web.Lists["mylib"];
foreach(SPListItem folder in mylib.Folders)
{
deleteVersions(SPFolder folder);
}
protected void deleteVersions (SPFolder folder)
{
foreach (SPFile file in folder.Files.Count)
{
foreach(SPFileVersion version in file.Versions)
{
Version.Delete();
}
}
}
Well, unfortunately, it is not quite that simple. This will throw an error and notify you that the enumeration has been modified. The count is read dynamic, and on next iteration it does not sync since you have deleted something.
In order to overcome this issue we will take a different approach:

SPSite site = new SPSite(“http://yoursite/”);
SPWeb web = site.AllWebs["TestSite"];
SPDocumentLibrary mylib= (SPDocumentLibrary)web.Lists["mylib"];
foreach(SPListItem folder in mylib.Folders)
{
deleteVersions(SPFolder folder);
}
protected void deleteVersions (SPFolder folder)
{
for (int i = 0; i < folder.Files.Count; i++)
{
SPFile file = folder.Files[i];
int counter = file.Versions.Count;
for (int j = 0; j < counter – 1; j++)
{
if (file.Versions[0] != null)
{
file.Versions[0].Delete();
}
}
}
}
In this snippet we are saving the count to local variable to make it static
int counter = file.Versions.Count;
Then iterating through the collection and subtracting counter – 1” from static enumeration. Which allows us to iterate through collection of files delete without getting that annoying error.

Comments