Hey people!
This post I want to share a code very useful when you need to copy files between libraries and you need to keep versioning.
In fact I search on internet a lot but when I believe there is no solution to this issue I found an article very interesting talking about sharepoint versioning and copying files.
I expect that the code bellow could be useful for you and if you have any question, just let me know.
Until next Post!
// Constant Declaration
const string fromDocTitle = "From";
const string toDocTitle = "To";
const string siteName = "http://sharepoint:204";
const string websiteName = "";
static void Main(string[] args)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedSiteColl = new SPSite(siteName))
{
using (SPWeb ElevatedSiteFrom = ElevatedSiteColl.OpenWeb("abc"))
{
using (SPWeb ElevatedSiteTo = ElevatedSiteColl.OpenWeb(""))
{
SPFileCollection collFrom = ElevatedSiteFrom.Folders[fromDocTitle].Files;
SPFileCollection collTo = ElevatedSiteTo.Folders[toDocTitle].Files;
SPDocumentLibrary docLib = (SPDocumentLibrary)(ElevatedSiteTo.Lists[collTo.Folder.ContainingDocumentLibrary]);
docLib.EnableMinorVersions = true;
docLib.Update();
byte[] binFrom = null;
SPFile file = null;
string url = "";
foreach (SPFile fileFrom in collFrom)
{
Console.WriteLine("Copying File " + fileFrom.Name);
SPFileVersionCollection versions = fileFrom.Versions;
foreach (SPFileVersion version in versions)
{
try
{
Console.WriteLine("Copying Version " + version.VersionLabel);
url = fileFrom.Url.Replace(fromDocTitle, toDocTitle);
binFrom = version.OpenBinary();
file = collTo.Add(url, binFrom, version.CreatedBy, version.CreatedBy, version.Created, version.Created);
file.Item["Created"] = version.Created;
file.Item["Modified"] = version.Created;
file.Item.UpdateOverwriteVersion();
file.Publish(version.CheckInComment);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace + "\n" + ex.Message);
}
}
url = fileFrom.Url.Replace(fromDocTitle, toDocTitle);
binFrom = fileFrom.OpenBinary();
file = collTo.Add(url, binFrom, fileFrom.ModifiedBy, fileFrom.ModifiedBy, fileFrom.TimeCreated, fileFrom.TimeLastModified);
file.Item["Created"] = fileFrom.TimeCreated;
file.Item["Modified"] = fileFrom.TimeLastModified;
file.Item.UpdateOverwriteVersion();
file.Publish(fileFrom.CheckInComment);
}
docLib.EnableMinorVersions = false;
docLib.Update();
}
}
}
});
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace + "\n" + ex.Message);
}
}
No comments:
Post a Comment