Team blog of MCS @ Middle East and Africa

This blog is created by Microsoft MEA HQ near shoring team, and it aims to share knowledge with the IT community.With its infrastructure and development sides,It brings to you the proven best practices and real world experiences from Subject Matter Experts
Follow Us On Twitter! Subscribe To Our Blog! Contact Us

Reading item attachments programmatically (SPFile.OpenBinary Exception)

Reading item attachments programmatically (SPFile.OpenBinary Exception)

  • Comments 3
  • Likes

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.

  • 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 . ?

  • Thank you my friend, that was very helpful

  • Thank you, its useful

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment