65.9K
CodeProject is changing. Read more.
Home

Programatically Copy all SharePoint List Items to Another List from Another Site with Attachments

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Aug 23, 2016

CPOL
viewsIcon

20691

Copy all list items along with attachment to another List (same site, another site, another site collection) using managed client object model

Introduction

Copy all list items along with attachment to another List (same site, another site, another site collection) using managed client object model.

Background

Sometimes, we need to copy all listitems from one list to another exactly same list. For example, archiving list data. Following is the useful code. I have written this code is client object model so it will also work in Sharepoint online.

Using the Code

Following is the code to copy all list items. I have copied this code from my existing application. You can directly call method "MigrateListItemsWithAttachments".

private static void MigrateItems(string ListName, string sourceSiteUrl, string destSiteUrl)
        {
            string sourceAccessToken = GetToken(sourceSiteUrl);
            try
            {
                using (ClientContext sourcecontext = 
                  TokenHelper.GetClientContextWithAccessToken(sourceSiteUrl, sourceAccessToken))
                {
                    MigrateListItemsWithAttachments(ListName, sourcecontext, destSiteUrl);
                }
            }
            catch (Exception ex)
            {
                //log exception
            }
        }

 private static void MigrateListItemsWithAttachments
(string listName, ClientContext sourceContext, string destSite)
        {
            List sourceList = null;
            ListItemCollection itemsToMigrate = null;
            List destinationList = null;            
            string siteUserName = "";
            try
            {
                sourceList = sourceContext.Web.Lists.GetByTitle(listName);
                itemsToMigrate = sourceList.GetItems(CamlQuery.CreateAllItemsQuery());
                sourceContext.Load(itemsToMigrate);
                sourceContext.ExecuteQuery();

                string sitePassword = Convert.ToString
                                      (ConfigurationManager.AppSettings["SharePointPassword"]);
                SecureString securePassword = new SecureString();
                foreach (char c in sitePassword) { securePassword.AppendChar(c); }
                using (ClientContext destContext = new ClientContext(destSite))
                {
                    destContext.Credentials = new SharePointOnlineCredentials
                                              (siteUserName, securePassword);
                    destinationList = destContext.Web.Lists.GetByTitle(listName);
                    destContext.Load(destinationList.Fields);
                    destContext.ExecuteQuery();
                    //Migrating data.
                    foreach (ListItem item in itemsToMigrate)
                    {
                        ListItemCreationInformation itemInfo = new ListItemCreationInformation();
                        ListItem itemToCreate = destinationList.AddItem(itemInfo);
                        AttachmentCollection attachmentCollection = item.AttachmentFiles;
                        foreach (Field field in destinationList.Fields)
                        {
                            if (!field.ReadOnlyField && !field.Hidden && 
                                 field.InternalName != "Attachments")
                            {
                                try
                                {
                                    itemToCreate[field.InternalName] = item[field.InternalName];
                                }
                                catch (Exception ex)
                                {
                                    //Log exception
                                }
                            }
                        }
                        itemToCreate.Update();
                        destContext.ExecuteQuery();
                        UpdateAttachments
                           (sourceContext, destContext, item.Id, itemToCreate.Id, listName);
                    }
                }
            }
            catch (Exception ex)
            {
                //Log exception               
            }
        }

        private static void UpdateAttachments(ClientContext srccontext, 
              ClientContext dstcontext, int srcItemID, int destItemID, string listName)
        {
            try
            {
                //getting attachment from files
                Web srcweb = srccontext.Web;
                srccontext.Load(srcweb);
                srccontext.ExecuteQuery();
                string src = string.Format("{0}/lists/{1}/Attachments/{2}", 
                                  srcweb.Url, listName, srcItemID);
                Folder attachmentsFolder = srcweb.GetFolderByServerRelativeUrl(src);
                srccontext.Load(attachmentsFolder);
                FileCollection attachments = attachmentsFolder.Files;
                srccontext.Load(attachments);
                srccontext.ExecuteQuery();

                if (attachments.Count > 0)
                {
                    foreach (Microsoft.SharePoint.Client.File attachment in attachments)
                    {                       
                        ClientResult<Stream> clientResultStream = attachment.OpenBinaryStream();
                        srccontext.ExecuteQuery();
                        var stream = clientResultStream.Value;

                        AttachmentCreationInformation attachFileInfo = 
                                                     new AttachmentCreationInformation();
                        Byte[] buffer = new Byte[attachment.Length];
                        int bytesRead = stream.Read(buffer, 0, buffer.Length);
                        System.IO.MemoryStream stream2 = new System.IO.MemoryStream(buffer);
                        attachFileInfo.ContentStream = stream2;
                        attachFileInfo.FileName = attachment.Name;                     

                        Web destweb = dstcontext.Web;
                        List destlist = destweb.Lists.GetByTitle(listName);
                        ListItem destitem = destlist.GetItemById(destItemID);
                        dstcontext.Load(destitem);
                        dstcontext.ExecuteQuery();
                        Attachment a = destitem.AttachmentFiles.Add(attachFileInfo);
                        dstcontext.Load(a);
                        dstcontext.ExecuteQuery();
                        stream2.Close();
                    }
                }
            }
            catch (Exception ex)
            {
               //Log exception
            }
        }