Tuesday, October 30, 2012

Copy all list items with attachments to other list(s) programmatically

Sometime, we find requirement from business to create a copy of a SharePoint list with all its contents including all attachments. If size of list is larger and we try to save list as a template with its contents, it gives error.

To do this task, we need to write little code which will copy all list items to the destination list. To execute code below successfully, it is necessary that both lists have same schema. To achieve it, follow these steps,

  • Save destination list as a template.
  • Create a new list using template we just created.
  • Copy this code in our Visual Studio and supply correct Site URLs and list names. We can change variables and parameters as per our requirement.
  • Run the code on SharePoint Server.

            string SourceSiteUrl = "http://SPServer";
            string DestSiteUrl = "
            string SourceListName = "Source List";   
            string DestinationListName = "Destination List";  
            SPSite SourceSite = new SPSite(SourceSiteUrl);  
            SPWeb SourceWeb = SourceSite.RootWeb;  
            SPList sourceList = SourceWeb.Lists[SourceListName];
            SPSite DestSite = new SPSite(DestSiteUrl);   
            SPWeb DestWeb = DestSite.RootWeb;     
            SPList destList = destWeb.Lists[DestinationListName]; 
            foreach (SPListItem sourceItem in sourceList.Items) 
                SPListItem newDestItem = destList.Items.Add(); 
                foreach (SPField field in sourceList.Fields) 
                    if (!field.ReadOnlyField && field.Type != SPFieldType.Attachments)
                        newDestItem[field.InternalName] = sourceItem[field.InternalName]; 

                if (sourceItem.Attachments.Count > 0) 
                    SPFolder sourceItemAttachFolder = sourceItem.Web.Folders["Lists"].SubFolders[sourceItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];  
                    foreach (SPFile file in sourceItemAttachFolder.Files)  
                        byte[] binFile = file.OpenBinary();       
                        newDestItem.Attachments.AddNow(file.Name, binFile);
            Console.WriteLine(destList.Title + " updated successfully.");

This code will copy all list items with all attachments to the destination list. Using this code, we can create copies of lists in other site collections too. This code will fail if both source and destinations lists would have different schema.


  1. Are you trying to earn cash from your websites/blogs by popup advertisments?
    In case you are, did you take a look at Propeller Ads?

  2. Can you do this in client side only. using java script or jquery