Copy Sharepoint list items from one site to another programmatically

25 August, 2009 (06:13) | MOSS - Object Model | By: G Vijai Kumar

In my earlier post, I have show you how to Copy items from one list to another, using Sharepoint designer workflow now we learn how to copy list items from one Sharepoint site to another site programmatically

Before executing the code I have created two Sharepoint sites, first is http://fivenumber:5/ and the second http://fivenumber:50/

I have also created custom list in each site, Source List in site http://fivenumber:5/ and Desitination List in http://fivenumber:50/

Here in this scenario I have chosen Console Application template because it doens’t contains any input fields to show as webpart and also to avoid GAC registration, safe controls etc., I felt it will be easy to execute the code in Console.

Download complete source code

Source List

Source List

Copied List Items

Copied List Items

Destination List

Destination List

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SharePoint;

namespace CopyListItems
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SPSite mySourceSite = new SPSite("http://fivenumber:5/");
                SPWeb mySourceWeb = mySourceSite.OpenWeb();
                SPList mySourceList = mySourceWeb.Lists["Source List"];
                SPQuery mySourceListQuery = new SPQuery();
                mySourceListQuery.Query = "" +
                                "" +
                                "" +
                                "" +
                                "";
                SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);
                int count = 0;
                foreach (SPListItem mySourceListItem in mySourceItemColl)
                {
                    string SourceEmpId = mySourceListItem["Employee Id"].ToString();
                    string SourceEmpName = mySourceListItem["Employee Name"].ToString();
                    string SourceDesig = mySourceListItem["Designation"].ToString();
                    string SourceAge = mySourceListItem["Age"].ToString();

                    SPSite myDestinationSite = new SPSite("http://fivenumber:50");
                    SPWeb myDestinationWeb = myDestinationSite.OpenWeb();
                    SPList myDestinationList = myDestinationWeb.Lists["Destination List"];
                    SPListItem myDestinationListItem = myDestinationList.Items.Add();

                    myDestinationListItem["Employee Id"] = SourceEmpId;
                    myDestinationListItem["Employee Name"] = SourceEmpName;
                    myDestinationListItem["Designation"] = SourceDesig;
                    myDestinationListItem["Age"] = SourceAge;
                    myDestinationWeb.AllowUnsafeUpdates = true;
                    myDestinationListItem.Update();
                    myDestinationWeb.AllowUnsafeUpdates = false;
                    count++;
                    Console.WriteLine(count+" item(s) copied");
                }
                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
        }
    }
}

If you have Lookup column in your Source List and want to copy the same data in to Destination List, you have to create an instance for SPFieldLookupValue class like below…..

Let’s suppose ‘Employee Name’ column is lookup field, comment or remove the line # 29 in the above code and replace with below code snippet

SPFieldLookupValue mySourceLookupEmpName = new SPFieldLookupValue(mySourceListItem["Employee Name"].ToString());
string SourceEmpName = mySourceLookupEmpName.LookupId.ToString();

Comments

Pingback from Copy item from one list to another, using Sharepoint designer workflow
Time August 25, 2009 at 6:27 am

[...] to copy list items from one Sharepoint site to another programmatically, please have a look at this post Source List Copy Item Workflow – Sharepoint Designer Source List Destination [...]

Comment from Naresh
Time January 15, 2010 at 9:59 pm

Hi Vijay,
nice work.. do you know how can we keep the created,modified date and modified by for the item we are copying in the destination list.

Comment from G Vijai Kumar
Time January 18, 2010 at 7:03 am

@Naresh: Try the below code to update the created, modifed date, modified by fields
mySPListItem["Created"] = new DateTime(2010, 1, 18); // you can set your own date
mySPListItem["Modified"] = System.DateTime.Now; // you can set your own date
mySPListItem["Modified By"] = “domain\accountname”; // you can set your account name
mySPListItem.UpdateOverwriteVersion(); //Updates the item without creating another version of the item

Comment from Naresh
Time January 18, 2010 at 5:51 pm

Thanks Vijay, I am working for a similar solution where I have a Document library with more than 2000 documents. and user has the ability to mention the Expiration of each document by mentioning the date in a custom created datefield column. if for any reason user does not mention any expiration date with in that custom column system should set the expiration date based on the last modified date which is (modified date+365). I have tried to implement this formula in a console application and set the expiration date. which is check the custom expiration column, if there is a date field set the date as Expiration date otherwise set expiration date as ( Modified + 365) which i was able to set successfully without modifying the Modified or create fields. and probem starts for me when copying those documents which are expired into a seprate Archve library. my first attempt to cpoy the the expired items is creating a custom expiration forumula which was same as the logic that i mentioned to check the custom date field and set the expiration date and as you know that we have Information maagement policy and where we implement this custom expiration formula. I have crated a workflow in Designer to copy the documents into the Archive Document Library up on successfull execution of the custom expiration formula. after running this expiration i can see only 95 documents copied over to the Archive Library and there are 500 more documents remained in the original document library whose modified date satisfied my condition that it has not been touched since 1 year and which needs to be expired or archived acording to my requirement. so i am thinking it is better to implemen the copy logic in console application itself so that i dont have to deal with the expiration formula.. in doing so your code is exactly what i need but have a different if condition.. here is my if condition based up on that condition copy should occur..
if (System.DateTime.Compare(docexpirationdate, todayminusthreesixtyfive) < 0)
{}
where docexpiration date is set based up on the following code
for (int i = 0; i < list.ItemCount; i++)
{

SPListItem item = list.Items[i];
object expDate = item["Document Expiration Date"];
if (expDate != null)
{
Expiration.SetExpirationDateForItem(item, Convert.ToDateTime(expDate), false);

}
else if (expDate == null)
{
object defaultExp = item["Last_x0020_Modified"];
expDate = Convert.ToDateTime(defaultExp).AddDays(365);
Expiration.SetExpirationDateForItem(item, Convert.ToDateTime(expDate), false);
}
and todayminus365 is the date field that returns an year old date.
so up on this condition i want to execute the copy operation.. my first question is do i need to implement spquery as the way you did. can i use the same logic that you used to copy.

its a long mesage but sorry i have to start from the begining…

Comment from vasu
Time January 19, 2010 at 5:00 am

how to copy the list from one site to another site using Feature

Write a comment