Friday, 13 May 2011

copy splist item attachment to another splistitem

In my recent project there was requirement where i have to attach an attachement from one item to another item.
I have written the follwoing code snipet to do the same :


//Initialize the source and target item
SPListItem sListItem = null, tListItem = null;

//get the folder with the attachments for the source list item
SPFolder sListItemAttachmentsFolder = sListItem.Web.Folders["Lists"].SubFolders[sListItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sListItem.ID.ToString()];

//Loop over the attachments, and add them to the target list item
foreach (SPFile file in sListItemAttachmentsFolder.Files)
{
byte[] sFile = file.OpenBinary();
tListItem.Attachments.AddNow(file.Name, sFile);
}



//Update the target listitem to save the changes
tListItem.Update();