Copy a SharePoint List Programmatically

I've been working with the SharePoint API lately. One of my tasks is to copy SharePoint lists from one site to another site. This can be done in code as long as the two sites are on the same machine. It's OK if they are in different web applications, but it can't be from one server to another. If you need to copy from one server to another, you either need to do an export/import, or find a way to save the settings and import them on the new machine. I believe you can use the SharePoint Web Services to accomplish this, though. I haven't worked with that yet.

Anyway, it took a lot of digging around to figure out all the things I needed to copy lists, so I thought I'd post the code that is working for me. This post is only going to cover copying a basic list. I am planning on several more posts to handle document libraries, wikis, and other special cases. Each has their own challenges.

The requirements for me are to copy the bulk of the lists of a large SharePoint site to a new site with a different structure. Therefore, content and deploy is not going to work. Also, they are redesiging the pages, so they really only wanted the lists. What I'm doing is creating a new list on the new site and copying all the properties, so any metadata, such as who last modified the list, is unfortunately lost.

Here's the code:

// Instantiate web instances
SPSite sourceSite = new SPSite(@"http://SharePointServer:31001");

SPWeb sourceWeb = sourceSite.RootWeb;
SPSite destSite = new SPSite(@"http://SharePointServer:31002");
SPWeb destWeb = destSite.RootWeb;

// Get a reference to the source list
SPList sourceList = sourceWeb.GetList("/Lists/Announcements");

 
// if the list exists on the destination site, delete it

try
{
   SPList temp = destWeb.Lists[sourceList.Title];
   destWeb.Lists.Delete(temp.ID);
}
catch { }

// create new list on the destination web with same properties
Guid newListID = destWeb.Lists.Add(sourceList.Title, sourceList.Description,
                                   sourceList.BaseTemplate);

SPList destList = destWeb.Lists[newListID];

// copy items
foreach (SPListItem item in announcements.Items)
{
   SPListItem newDestItem = destList.Items.Add();
   foreach (SPField field in sourceList.Fields)
   {
      if (!field.ReadOnlyField)
      newDestItem[field.Id] = item[field.Id];
   }
   newDestItem.Update();
}

// set quicklaunch settings
destList.OnQuickLaunch = sourceList.OnQuickLaunch;
destList.Update();

Comments

Popular posts from this blog

SharePoint 2016 and 2019 Ports

PsConfig step by step /Configuration Wizard. “Upgrade Available” vs “Upgrade required”

Unlock the SharePoint site using Powershell command