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.