Tuesday, 3 November 2020

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

 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

            }

        }

No comments:

Post a Comment