Monday, October 12, 2009

Copy an existing item to another list

I wanted to copy an existing item to another list. I found a solution here but it didn't work for me fully.
Item I was trying to copy are inside a folder with the list.

Solution i found was copying items at the root level. But as my items were inside the folder , I wanted to copy over to new list in same folder. Here's modified code.


public static SPListItem CopyItem(SPListItem sourceItem, string destinationListName)
//copy sourceItem to destinationList
SPList destinationList = sourceItem.Web.Lists[destinationListName];
string folderName = "/" + itemToCopy.Url.Remove(itemToCopy.Url.LastIndexOf('/'));

SPListItem targetItem = destinationList.Items.Add(folderName, SPFileSystemObjectType.File);

foreach (SPField f in sourceItem.Fields)
if (!f.ReadOnlyField && f.InternalName != "Attachments")
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;
Copying over a SharePoint list from source site to destination site
Copy or move Sharepoint list items using SPExport and SPImport
SPListItem.CopyTo does not copy


Archana February 8, 2012 at 6:18 AM  

Is there any way to copy large number of list items to a SPList through a sandbox solution? I tried using ProcessBatchData; but it fails giving this errortext in output XML string - The operation failed because an unexpected error occurred. (Result Code: 0x80020005)

Any idea?

Sandeep K Nahta February 8, 2012 at 9:38 AM  

While there are ways to copy items, but with client object model you will surely face lot of issues. May be you can write a WCF with the main code and call it via jQuery Ajax by passing required parameters.