Friday, August 22, 2014

SharePoint Move/Copy all items of a document library to another from one SharePoint application to another

https://nasironline.wordpress.com/tag/move-document-library-items-using-client-object-model/

These two SharePoint Web applications are on different servers (cross server) so we need to use client object model, if there is a requirement to move items of one document library to another of two applications residing on same server then we can use Server Object Model.
Server Object Model (for same SharePoint server)

private void MoveDocumentsServerObjectModel(string sourceWebUrl, string sourceDocLib, string destWebUrl, string destDocLib)
{
try
{
using (SPSite sourceSite = new SPSite(sourceWebUrl))
{
using (SPWeb sourceWeb = sourceSite.OpenWeb())
{
sourceWeb.AllowUnsafeUpdates = true;
SPDocumentLibrary sourceDocumentLibrary = (SPDocumentLibrary)sourceWeb.Lists[sourceDocLib];
SPFileCollection sourceWebFiles = sourceDocumentLibrary.RootFolder.Files;
//Connecting to destination web
using (SPSite destSite = new SPSite(destWebUrl))
{
using (SPWeb destWeb = destSite.OpenWeb())
{
destWeb.AllowUnsafeUpdates = true;
SPDocumentLibrary destDocumentLibrary = (SPDocumentLibrary)destWeb.Lists[destDocLib];
foreach (SPFile sourceFile in sourceWebFiles)
{
destDocumentLibrary.RootFolder.Files.Add(destWeb.Url + "/" + destDocumentLibrary + "/" + sourceFile.Name, (Stream)sourceFile.OpenBinaryStream(), true);
}
destWeb.AllowUnsafeUpdates = false;
lblStatus.Text = "Moved successfully.";
}
}
sourceWeb.AllowUnsafeUpdates = false;
}
}
}
catch (Exception ex)
{
lblStatus.Text = ex.ToString();
}
}

Client Object Model (for Different SharePoint server)

private void CopyDocuments(string srcUrl, string srcLibrary, string destUrl, string destLibrary)
{
// set up the src client
ClientContext srcContext = new ClientContext(srcUrl);
// set up the destination context
ClientContext destContext = new ClientContext(destUrl);
// get the source list and items
Web srcWeb = srcContext.Web;
List srcList = srcWeb.Lists.GetByTitle(srcLibrary);
ListItemCollection itemColl = srcList.GetItems(new CamlQuery());
srcContext.Load(itemColl);
srcContext.ExecuteQuery();
// get the destination list
Web destWeb = destContext.Web;
destContext.Load(destWeb);
destContext.ExecuteQuery();
foreach (var doc in itemColl)
{
try
{
//if (doc.FileSystemObjectType == FileSystemObjectType.File) //Field or Property "FileAttachement not found."
//{
// get the file
File file = doc.File;
srcContext.Load(file);
srcContext.ExecuteQuery();
// build destination url
string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + file.Name;
// read the file, copy the content to new file at new location
FileInformation fileInfo = File.OpenBinaryDirect(srcContext, file.ServerRelativeUrl);
File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
// }
}
catch (Exception ex)
{
throw ex;
}
}
}

No comments: