3

How to copy documents and files from one site collection to another site collection using CSOM code?

1 Answer 1

7
 public void CopyDocuments(string srcUrl, string destUrl, string destLibrary)
        {
            ClientContext srcContext = new ClientContext(srcUrl);

            ClientContext destContext = new ClientContext(destUrl);

            Web srcWeb = srcContext.Web;

            List srcList = srcWeb.Lists.GetByTitle(srcLibrary);

            Web destWeb = destContext.Web;

            destContext.Load(destWeb);

            destContext.ExecuteQuery();
            try
            {
                Microsoft.SharePoint.Client.File file = srcContext.Web.GetFileByServerRelativeUrl("/sites/Publishing/test.pdf");
                srcContext.Load(file);
                srcContext.ExecuteQuery();
                string location = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + file.Name;
                FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(srcContext, file.ServerRelativeUrl);
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(destContext, location, fileInfo.Stream, true);
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

Method usage

CopyDocuments("URL1", "URL2", "Documents");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.