Deprecated: YoastSEO_Vendor\Symfony\Component\DependencyInjection\Container::__construct(): Implicitly marking parameter $parameterBag as nullable is deprecated, the explicit nullable type must be used instead in /home/nubelus/sharedove/adisjugo/wp-content/plugins/wordpress-seo/vendor_prefixed/symfony/dependency-injection/Container.php on line 60
Retrieving old file versions through code - Adis Jugo blog
Select Page

Retrieving old file versions through code

This blog post was included in “” selection from May 11th 2012.

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:

Cheers!

Previous

Next