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:
//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