Migrate documents in SharePoint without changing Author Name
Here is the code snippet that can be used for this purpose.
private void EventHandler_OnClick(object sender, System.EventArgs e){
//assuming that we are moving forms from "http://localhost/OldFormHome" to "http://localhost:12345/NewFormHome"
//and change all forms author to be testuser
//Get the old site
SPSite myOldSiteCollection = new SPSite("http://localhost");
SPWeb myOldRootSite = myOldSiteCollection.RootWeb;
SPListCollection oldLists = myOldRootSite.Lists;
oldLists.IncludeRootFolder = true;
//get the forms library folder
SPList oldList = oldLists["OldFormHome"];
SPFileCollection oldFiles = oldList.RootFolder.Files;
//Get the new site
SPSite myNewSiteCollection = new SPSite("http://localhost:12345");
SPWeb myNewRootSite = myNewSiteCollection.RootWeb;
SPUserCollection newUsers = myNewRootSite.AllUsers;
//Find the new user - user may have different Id, so we will have to have a way to map the Id
//in the real implementation
//**************************************************************/
//need to add code to make sure the user exists. Otherwise, exception thrown
//this will be the user set us author (createdBy) when the document is moved to the new library
SPUser user = newUsers["MYDOMAIN\\testuser"];
//get the new form lib
myNewRootSite.AllowUnsafeUpdates = true;
SPListCollection newLists = myNewRootSite.Lists;
newLists.IncludeRootFolder = true;
SPList newList = newLists["NewFormHome"];
SPFileCollection newFiles = newList.RootFolder.Files;
string newUrl ;
//loop through all the form files in the old fold and move to the new library
foreach (SPFile oldFile in oldFiles)
{
newUrl = newFiles.Folder.Url + "/" + oldFile.Name;
System.Diagnostics.Debug.WriteLine(newUrl);
newFiles.Add(newUrl ,
oldFile.OpenBinary(),
user,
user,
DateTime.Now, //we can also keep this as the old doc if needed
DateTime.Now);
}
myNewRootSite.AllowUnsafeUpdates = false;
}

No comments:
Post a Comment