Tuesday, February 17, 2009

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();
  }
}

No comments:

Post a Comment

Users cannot see the checked out files in the folder/ library

I Came across a Issue today wherein the user opened a ticket for the below issue Issue : Users cannot see the checked out files in the fo...