Programmatically copy items from one list to another in SharePoint 2010


I have a custom list named "Test" which has the following items

copyitems.jpg

I have one more custom list named "CopyTest" where I want to copy the items from "Test" list.


Code Snippet:

 

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();

                        }

                    }                  

                }

            }

        }

    }

}