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

Comment from Anu
Time April 5, 2010 at 9:41 pm

Hi

How to move data from One Sharepoint site to external Sharepoint site using out of box web service

Comment from Trappist
Time April 6, 2010 at 10:58 am

Hi,
This code works OK if both SourceSite and TargetSite are on the same farm and same credentials are being used.
But what if I am running this code on my TargetSite Server and what If my SourceSite is sitting on a different farm(requires different credentials). Which modification I need to do?
Thank you

Comment from Datta
Time April 16, 2010 at 12:34 pm

I want transfer document form SPList from one site to Other site. Both the sites are in different Farm. How I can achieve this?. For Eg. one document is kept in this site “http://server1/list” now Want to transfer to Second site i.e. on “http://server2/list”. Appriciate Your Help Thanks

Comment from ankit
Time May 7, 2010 at 6:54 am

Hi,Your document is of gr8 help.But i want to know that if i am using my first list on a web page where i am filtering my results with the help of dropdown list.i want those filtered results to be moved to second list.How to do that.Plz suggest.

Comment from G Vijai Kumar
Time May 25, 2010 at 6:18 am

@ Ankit: You can use CAML query, then based on filter you can move/copy only those particular items

Comment from Datta
Time May 25, 2010 at 6:24 am

@Hi,

If I want to Manage the permission using Sharepoint object model then ? while transferring from same to site list to same another list. Thanks

Comment from G Vijai Kumar
Time May 25, 2010 at 6:30 am

@ Datta: What permissions you want to manage exactly? do you want to set list permissions while copying items from one list to another?
Please provide more information, thanks

Comment from Datta
Time May 25, 2010 at 7:09 am

Thanks for your reply. Item level persmission. Suppose user has set permission as Reader to one documen & Contributor for another document using out of box SP Manage Permsiion Menu. Then same Persimmision should assign to document/Item which transfer to other document list. I wrote sample code snippest but It throws Error 4 me.
site.WebApplication.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;
SPUser user = web.CurrentUser;

SPRoleDefinition RoleDefinitionRdr = web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)user);
roleAssignment.RoleDefinitionBindings.Add(RoleDefinitionRdr);

Then MyQuestionListItem.Roleassignment.Add(roleAssignment)

but It throwing Error Message like -
1. The security validation for this page is invalid & another on is
2. Operation is not valid due to the current state of the object

If you have pointer then please let me know how I can achieve this.

Also Please let me know If you have know something about my query dated “Datta Time April 16, 2010 at 12:34 pm”

Once agian Thanks

Write a comment