GD Bloggers

This is the blog site for Microsoft Global Delivery Communities focused in sharing the technical knowledge about devices, apps and cloud.
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 4
  • 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.

Comments
  • 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 ..do i need to give any special kind of permission . ?

  • Thank you my friend, that was very helpful

  • Thank you, its useful

  • your probably looking at security issue here

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