SharePoint: How to retrieve specific version of file from a document library thro’ programmatically?


The SPFile.Versions API can be used to retrieve the specific version of the document library.


 


I have compiled a sample code snippet to retrieve the specific version of the document library.


 


            //Open the web


            SPWeb web = new SPSite(“http://karthickmain:9091/sites/siteb”).OpenWeb();


            //Get the folder


            SPFolder folder = web.Folders[“Shared Documents”];


            //Get the file


            SPFile file = folder.Files[“abc.doc”];


            //Get all the versions


            SPFileVersionCollection versions = file.Versions;


            //Get the first version


            SPFileVersion version = versions[3];


           


            //Get the data


byte [] dBytes = version.OpenBinary();


 


 


How to restore a specific version back to the document library thro’ programmatically?


 


There are two ways we can restore the document.


1.      SPFileVersionCollection.Restore() method


                        //restore specific version


versions.Restore(3);


 


2.      SPFile.SaveBinary() method


file.SaveBinary(versions[3].OpenBinary());


 


But however the Restore method is more efficient as per msdn


 


LINKS:


=======


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/spptsdk/html/tscSPFileVersionCollection_SV01013561.asp


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/spptsdk/html/tsmSPFileVersionCollectionRestore_SV01013756.asp

Comments (4)

  1. BobC says:

    Thanks Karthick.  

  2. qzb says:

    Great!But will the SPFileVersion Object exist in database if the SPFile object is deleted?

  3. Amit Naik says:

    Great, I've written a brief blog on a slight difference between SPFile.Versions and SPListItem.Versions :

    sharepointer2010.blogspot.com/…/file-version-history-c.html