Wednesday, August 28, 2013

Programmatically copy items from one list to another in SharePoint 2010


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;

namespace Console
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://serverName/sites/Vijai/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList sourceList = web.Lists.TryGetList("Test");
                    foreach (SPListItem sourceItem in sourceList.Items)
                    {
                        SPList destinationList = web.Lists.TryGetList("CopyTest");
                        if (destinationList != null)
                        {
                            SPListItem destItem = destinationList.Items.Add();
                            foreach (SPField field in sourceItem.Fields)
                            {
                                if (!field.ReadOnlyField && !field.Hidden && field.InternalName != "Attachments")
                                {
                                    if (destItem.Fields.ContainsField(field.InternalName))
                                    {
                                        destItem[field.InternalName] = sourceItem[field.InternalName];
                                    }
                                }
                            }
                            destItem.Update();
                        }
                    }                  
                }
            }
        }
    }
} 

No comments:

Post a Comment