How to copy attachments from one list item to another

The microsoft support article for WSS 2 shows us how to download attachments from a list item. Basically, the attachments for a list item are stored as SPFile objects under a hidden folder in the list where those attachments are (a folder called “Attachments”) – where each list item that has an attachment has its own folder – with the ID of the item being the folder’s name. Here is a code sample for a function to copy attachments from one item to another.

private void CopyAttachments(SPListItem sourceItem, SPListItem targetItem){

try {//get the folder with the attachments for the source item

SPFolder sourceItemAttachmentsFolder = sourceItem.Web.Folders[“Lists”].SubFolders[sourceItem.ParentList.Title] .SubFolders[“Attachments”].SubFolders[sourceItem.ID.ToString()];

//Loop over the attachments, and add them to the target item

foreach (SPFile file in sourceItemAttachmentsFolder.Files)

{byte[] binFile = file.OpenBinary();

targetItem.Attachments.AddNow(file.Name, binFile);}

} catch { }finally { sourceItem.Web.Dispose();}}

Ref : Sharepoint Tips And Tricks

Advertisements

One thought on “How to copy attachments from one list item to another”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s