Click here to Skip to main content
14,975,234 members
Articles / Productivity Apps and Services / Sharepoint / SharePoint 2013
Tip/Trick
Posted 22 Aug 2016

Stats

16.1K views
3 bookmarked

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
22 Aug 2016CPOL
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".

C#
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
            }
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

Comments and Discussions

 
QuestionUser Field Error Pin
Member 394480024-Aug-17 5:34
MemberMember 394480024-Aug-17 5:34 
Questionplease post getToken() function Pin
harsh13130-Apr-17 21:57
Memberharsh13130-Apr-17 21:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.