Retrieving Attachments from SharePoint List Items
This one had me beating my head against the wall for quite a while so I’m sharing it to save you the cost of a handful of Tylenol (or Paracetamol if you’re on the other side of the pond).
Each item in a SharePoint list has an associated SPAttachmentCollection array. It would seem logical that this array would function like most of the other object arrays in SharePoint and be comprised of SPAttachment or, more likely, SPFile objects so we could do the following:
SPAttachmentCollection attachments = listitem.Attachments;
foreach (SPFile file in attachments)
// Do something
No soup for you, dear reader, as doing that throws an invalid cast exception. Surprised? Well, so was I and it took me quite a while to figure out that the SPAttachmentCollection is simply an array of strings representing the file name of each attachment. Oh, joy, just what I needed. I’m not sure what good that does anyone, as there are actually several useful methods associated with the SPAttachmentCollection, like Add(), Delete(), and Recycle(), but there you have it.
So how do you get to the actual files themselves? Not easily or logically, I assure you. Here’s the way it’s done:
SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[listitem.ID.ToString()];
Then you can do:
foreach (SPFile file in folder.Files)
// Something useful here