C# – copy list items from one list to another in sharepoint

csharepoint

In Sharepoint how can you copy a list item from one list to another list
eg copy from "List A" to "List B" (both are at the root of the site)

I want this copying to occur when a new list item is added to "List A"

I tried using the CopyTo() method of an SPListItem inside the ItemAdded event receiver but couldnt figure out the url to copy to.

Best Answer

Here is the code I use. Pass it a SPlistItem and the name of the destination list as seen in Sharepoint(Not the URL). The only restriction is that both list must be in the same site:

private SPListItem CopyItem(SPListItem sourceItem, string destinationListName) {
        //Copy sourceItem to destinationList
        SPList destinationList = sourceItem.Web.Lists[destinationListName];
        SPListItem targetItem = destinationList.Items.Add();
        foreach (SPField f in sourceItem.Fields) {
            //Copy all except attachments.
            if (!f.ReadOnlyField && f.InternalName != "Attachments"
                && null != sourceItem[f.InternalName])
            {
                targetItem[f.InternalName] = sourceItem[f.InternalName];
            }
        }
        //Copy attachments
        foreach (string fileName in sourceItem.Attachments) {
            SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
            byte[] imageData = file.OpenBinary();
            targetItem.Attachments.Add(fileName, imageData);
        }

        return targetItem;
    }