Friday, May 11, 2012

Retrieving old file versions through Server Object Model

Recently I  have been asked about issue of retrieving old file versions from a SharePoint document library through server object model code, particulary check in comment for the major (published) versions.
The first try was to retrieve data from the .Versions property of the SPListItem, or, from SPListItem.File.Versions, if we are talking about document libraries and files.
And it worked – almost. The File.Versions property contains PREVIOUS file versions, and it does not hold the info on the current file version – this info is stored directly under the .File property.
Here is a functioning piece of code to retrieve check in comment (or any other version information, for that matter), both for current and previous versions:


using (SPSite site = new SPSite("http://localhost"))
{
    using (SPWeb web = site.OpenWeb())
    {
  
        SPList docsList = web.Lists["Shared Documents"];
  
        SPListItemCollection items = docsList.GetItems(new SPQuery());
  
        foreach (SPListItem item in items)
        {
            Console.WriteLine("");
            Console.WriteLine(item.File.Name);
            Console.WriteLine("=============");
            Console.WriteLine("Current version: " + item.File.UIVersionLabel);
            Console.WriteLine("Current version check in comment: " + item.File.CheckInComment);
  
            if (item.File.MajorVersion == 0) // return if there are no major version
                continue;
  
            Console.WriteLine("Old Versions:");
            Console.WriteLine("-------------");
            foreach (SPFileVersion version in item.File.Versions)
            {
                Console.WriteLine(version.VersionLabel  + " : " +  version.Level);
                Console.WriteLine("CheckIn Comment: " + version.CheckInComment);
                Console.WriteLine("");
            }
  
        }
  
    }
}
This code produces the following result for a file in document library, currently in a minor (draft) version 4.3:


dokument 1 in deutsch.docx
=============
Current version: 4.3
Current version check in comment: Comment to minor 4.3 version
  
Old Versions:
-------------
1.0 : Published
CheckIn Comment:
  
2.0 : Published
CheckIn Comment:
  
3.0 : Published
CheckIn Comment:
  
3.1 : Draft
CheckIn Comment:
  
4.0 : Published
CheckIn Comment: Some comment to 4.0
  
4.1 : Draft
CheckIn Comment:
  
4.2 : Draft
CheckIn Comment:

 

No comments:

Post a Comment

SharePoint AI Innovations Reach General Availability

Microsoft continues to strengthen the foundation for AI-powered workplaces with the announcement that several SharePoint AI innovations are ...