A few days I had a problem with the simple SharePoint thing, simple at the begging… I had to write EventReceiver to move list items to archive. Ok, as we know event receiver expose list item properties, which also has the obvious method CopyTo, which work perfectly with the document library, but when you try to use it with list item it can’t be used. Well, that’s was surprising. So what can we do? SharePoint Designer. Well, there’s the next surprise. With SharePoint designer, without custom actions, you can’t move an item to another site. So let’s go back to our event receiver. For me, there’s only one possibility. I had to copy column by column to the destination list. Also, you can copy in this way attachment. The client use SharePoint foundation and I didn’t have time to check possibilities of Enterprise or Standard versions like “send to”, Record center or moving document set task in SharePoint designer.    Anyway please find below the code which copy the list item to list on another site.

Please remember that the destination list must contain all source columns or the code will throw an exception! To avoid such a thing you can build a destination based on the source list template.

The code is:


namespace SharePointProject3.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item was updated.
/// </summary>
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);

try
{
CopyItem(properties.ListItem, properties.SiteId);
}
catch (Exception)
{
throw;
}
}

private SPListItem CopyItem(SPListItem sourceItem, Guid guid)
{
using (SPSite site = new SPSite(guid))
{
using (SPWeb web = site.AllWebs["DesinationSite"])
{

SPList destinationList = web.Lists["DesitnationList"]; //sourceItem.Web.Lists[destinationListName];
SPListItem destinationItem = destinationList.Items.Add();
foreach (SPField field in sourceItem.Fields)
{
if (!field.ReadOnlyField && field.InternalName != "Attachments" && null != sourceItem[field.InternalName])
{
destinationItem[field.InternalName] = sourceItem[field.InternalName];
}
}
destinationItem.Update();
//Copy attachments
foreach (string fileName in sourceItem.Attachments)
{
SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
byte[] imageData = file.OpenBinary();
destinationItem.Attachments.Add(fileName, imageData);
}
destinationItem.Update();
return destinationItem;
}
}
}
}
}