Friday, October 5, 2018

Moving/copying file with version history to another library (SharePoint 2010, 2013, 2016)

Recently, I had to copy an archive of documents from one collection of sites to another, I didn’t have any problems with PowerShell, thanks to Import\Export, but the task changed when the question arose about transferring several large documents with a long history of versioning from one library to another. I tried to find a solution without a code, but did not find anything, and suddenly in one forum I saw a small piece of code that solved my problems, in this article I will share it and tell you a little.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using System;

using Microsoft.SharePoint;

using System.IO;

using System.Collections;

//Get SPSite or Site Collection
using (SPSite oSPsite = new SPSite("http://sp/sites/test")){
 using (SPWeb oSPWeb = oSPsite.OpenWeb())
  {
   //Get Library source
   SPList lib_source = oSPWeb.Lists["Library1"];
   //Get Library destination
   SPList lib_destination = (SPDocumentLibrary)oSPWeb.Lists["Library2"];
   //Get item (file) using SPQuery
   SPListItemCollection items = lib_source.GetItems(new SPQuery()
    {
     Query = @"<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>Document.docx</Value></Eq></Where>"
      });
         foreach (SPListItem item in items) {
           SPFile fileSource = item.File;
           //Get the created by and created
           SPUser userCreatedBy = fileSource.Author;
           //Convert the "TimeCreated" property to local time
           DateTime dateCreatedOn = fileSource.TimeCreated.ToLocalTime();
           //Get the versions history
           int countVersions = item.File.Versions.Count;
              for (int i = 0; i <= countVersions; i++)
                {
                  Hashtable hashSourceProp;
                  Stream streamFile;
                  SPUser userModifiedBy;
                  DateTime dateModifiedOn;
                  string strVerComment = "";
                  bool bolMajorVer = false;
                    if (i < countVersions)
                     {
                      //Get all versions file, history, properties, createdBy, checkInComment
                      SPFileVersion fileSourceVer = item.File.Versions[i];
                      hashSourceProp = fileSourceVer.Properties;
                      userModifiedBy = (i == 0) ? userCreatedBy : fileSourceVer.CreatedBy;
                      dateModifiedOn = fileSourceVer.Created.ToLocalTime();
                      strVerComment = fileSourceVer.CheckInComment;
                      bolMajorVer = fileSourceVer.VersionLabel.EndsWith("0") ? true : false;
                      streamFile = fileSourceVer.OpenBinaryStream();
                     } else {
                       //Get current versions file, history, properties, createdBy, checkInComment
                       userModifiedBy = fileSource.ModifiedBy;
                       dateModifiedOn = fileSource.TimeLastModified;
                       hashSourceProp = fileSource.Properties;
                       strVerComment = fileSource.CheckInComment;
                       bolMajorVer = fileSource.MinorVersion == 0 ? true : false;
                       streamFile = fileSource.OpenBinaryStream();
                     }
                       //URL library destination
                       string urlDestFile = lib_destination.RootFolder.Url + "/Folder/" + fileSource.Name;
                       //Copy all properties
                       SPFile fileDest = lib_destination.RootFolder.Files.Add(
                         urlDestFile,
                         streamFile,
                         hashSourceProp,
                         userCreatedBy,
                         userModifiedBy,
                         dateCreatedOn,
                         dateModifiedOn,
                         strVerComment,
                         true);
                          if (bolMajorVer)
                             fileDest.Publish(strVerComment);
                          else
                            {
                             SPListItem itmNewVersion = fileDest.Item;
                             itmNewVersion["Created"] = dateCreatedOn;
                             itmNewVersion["Modified"] = dateModifiedOn;
                             itmNewVersion.UpdateOverwriteVersion();
                            }                  
                        }
                    }
                }
            }
Happy Coding!

No comments:

Post a Comment