Monday, April 23, 2012

All about SharePoint File Version History:


Lately I have been working on Sharepoint file version. Like how to display all the versions of SPFile, how to restore specific version and how to show current version of file.

Below are two class that gives you all the versions collection:

1.The SPListItemVersionCollection object contains all the versions, including the current one.
2.The SPFileVersionCollection object does not include the current version.


How to get all the information about versions:



SPFileVersionCollection versions = file.Versions;
 SPFieldUserValue userValue = new SPFieldUserValue(file.ParentFolder.ParentWeb, Convert.ToString(file.Item["Modified By"]));                   
                    if (versions != null)
                    {
                        foreach (SPFileVersion _version in versions)
                        {
                          string  fileURL = file.Versions.GetVersionFromLabel(_version.VersionLabel).Url;                          
                          string  displayName = web.EnsureUser(Convert.ToString(_version.CreatedBy)).Name;
                          int versionID=_version.ID;
                          string versionLabel= _version.VersionLabel;                           
                        }
                    }


After you have all the information you can bind the data to gridview.


How to open specific version in binary file:


SPWeb web= SPContext.Current.Web; // open the web where list exists.
SPList list= web.Lists["My List"]; // open the list where the file exists.
SPListItem  item = list.items[0]; // open the item. for now i am getting first item in list.
string FileVersionNumber="1.0";
SPFileVersionCollection verCollection= item.File.Versions; 

SPFileVersion version = versions.GetVersionFromLabel(FileVersionNumber);
 byteArray = version.OpenBinary();



How SharePoint generates URL for specific Version:


For each Published version SharePoint will have regular URL. For example, if the item is publish then its url will be :
        "/sitename/Lists/Listname/folder name/test.xlsx.


Lets say it has two major version, 1.0 and 2.0. Then what will be url of version 1.0?. It will be like shown below:
      " vti_history/512/Lists/mylist/myfolder/test.xlsx"
and version 2.0 will have regular URL.


SharePoint automatically adds number between its each major version. So version "1.0" will be "512", version "2.0" will have "1024" appended to URL and so on..


How to Restore specific version:


Lets say we want to restore version "1.0"


file.CheckOut();
file.Versions.RestoreByLabel(fileVersionLabel);
file.CheckIn(string.Empty); 




Tag: SharePoint, File Version.


~Happy Coding.

No comments: