Reading item attachments programmatically (SPFile.OpenBinary Exception)

This is a small issue that I faced the other day and wasted several hours of my time. The scenario is rather simple. You have a list item and you already have an attachment to this item. What you want to do is to read this item attachment in a workflow or a web part using code.

So you start off by writing the following code:

SPFile spFile = Item.Web.GetFile(Item.Attachments.UrlPrefix + Item.Attachments[0]);

byte[] binFile = spFile.OpenBinary();

Simple right? well you will eventually get an SPException in the OpenBinary function call and it will report that it cannot open the file!!!

So after several hours (and several cups of coffee) I was able to perform the needed functionality but by accessing the SPFile object using the folder collection and not the URL. This is how.

SPFolder folder = Item.Web.Folders["Lists"].SubFolders[Item.List.Title].SubFolders["Attachments"].SubFolders[Item.ID.ToString()];

SPFile spFile = folder.Files[Item.Attachments[0]];

byte[] binFile = spFile.OpenBinary();

BTW this happened on SharePoint 2010 and as far as I remember the old code used to work with no problems on SharePoint 2007.

Comments (4)

  1. Anonymous says:

    Thank you, its useful

  2. Rahul says:

    Hi, I have used same code to read attachment in list item in webpart. I am facing issue :  User member of home  visitor group is not able to view this attachment .code is not working ..But home owner able to view this attachment .Please guide me i need to give any special kind of permission . ?

  3. Haadka says:

    Thank you my friend, that was very helpful

  4. anwar says:

    your probably looking at security issue here