Skip to main content

Cloud

Getting files attached to an instance of SPListItem

I was doing something with file attachments on custom lists in SharePoint recently, and the solution to iterating through the attachments and retrieving the binary file information wasn’t readily obvious to me.
For example, adding new attachments is done with the Add method on the SPListItem’s Attachments collection. No problem.
newItem.Attachments.Add(fileName, contents);
// where "contents" is a byte[]
However, when you want to retrieve the existing attachments and iterate through the Attachments collection, the WSS object model returns you a string containing the name of the attached file:
foreach (string s in item.Attachments)
{
Debug.WriteLine(s); // this is the filename of the attachment
}
So how do you get the binary data back?
I expected the Attachments collection to contain items of a type other than string (SPAttachment sounded friendly enough to me, but no dice). I also thought perhaps the collection would have some kind of method exposed to return the byte array of an element at a given position, but that was a blind alley, as well.
So here’s the solution:
You have to call GetFile on the SPWeb instance that contains your SPListItem and pass it the full URL of the attachment. You can get the full URL with the UrlPrefix property of the attachment collection and the string filename returned by the attachment iterator.
Once you have an instance of SPFile, you can get at the binary data, etc.
foreach (string fileName in item.Attachments)
{
SPFile file = item.ParentList.ParentWeb.GetFile(
item.Attachments.UrlPrefix + fileName);
}
It makes sense now that I see it, although I still like the SPAttachment idea. Thanks to Mike for pointing me in the right direction; he does that a lot. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Matthew Morse

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram