During one of my projects we are writing a migration application for converting WSS 2.0 data to WSS 3.0 data. Yes, i know there are several methods from Microsoft to do migration but all of them were not sufficient enough :) So we are writing our own. One of the problems we encountered was copying files and their versions stored in SPFile and SPFileVersion objects. Trying a lot, following Microsoft documentation and reading a lot of discussions on the internet, we finally came up with the solution.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPGlobalAdmin admin = new SPGlobalAdmin();
SPVirtualServer vs = admin.OpenVirtualServer(new Uri(http://someurl/));
string fromDocTitle = "DocFrom";
string toDocTitle = "DocTo";
SPWeb rootWeb = vs.Sites[0].RootWeb;
SPFileCollection collFrom = rootWeb.Folders[fromDocTitle].Files;
SPFileCollection collTo = rootWeb.Folders[toDocTitle].Files;
byte[] binFrom = null;
SPFile file = null;
string url = "";
foreach (SPFile fileFrom in collFrom)
{
SPFileVersionCollection versions = fileFrom.Versions;
foreach (SPFileVersion version in versions)
{
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();
}
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();
}
});