Download Attachments from SharePoint ListItems

Published 29 December 08 08:23 AM | jacobl 

There are times when you might want to download an attachment from a SharePoint list item. In the case of Document Libraries, this is trivial because there is a File property associated with the SPItem that you can use to get access to the file. Unfortunately, the only information available to you about list item attachments is the SPAttachmentsCollection which is simply a list of strings (the names of the files). This is less than useful since it provides you with no information as to where those files might be.

My First Attempt

After a bit of poking around the object model, I finally gave up and came up with this:

   1: SPFolder folder = web.Folders["Lists"].SubFolders[list.RootFolder.Name].SubFolders["Attachments"].SubFolders[item.ID.ToString()];

Pretty insane, huh? I thought it was so terrible that I decided it was wrong and did some more research.

Research

First, I came across this blog which only disappointed me since Eric Shupps came up with the same thing. Even worse, the next result in my Google search was MSDN. Low and behold: How to Programmatically Download Attachments from List Items in Windows SharePoint Services. The hack is the official way to do things apparently.

Granted, it works fine. It's just not as elegant as it probably should be.

Another Problem

There is a problem that this still poses. You cannot enumerate through folders that you do not have Contributor access to. Users that only have View access will not be able to download files that they clearly have rights to download. Here's my fix for that situation:

   1: private SPFolder GetAttachmentsFolder(SPWeb web, SPListItem item)
   2: {
   3:     SPFolder folder = null;
   4:     SPSecurity.RunWithElevatedPrivileges(delegate()
   5:     {
   6:         using (SPSite elevatedSite = new SPSite(web.Site.ID))
   7:         using (SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID))
   8:         {
   9:             folder = elevatedWeb.Folders["Lists"].SubFolders[item.ParentList.RootFolder.Name].SubFolders["Attachments"].SubFolders[item.ID.ToString()];
  10:         }
  11:     });
  12:     return folder;
  13: }

You can then get the ith attachment from the folder. Since your call to folder.Files[index or file name] will not be in an elevated call, SharePoint will do the right thing and block unauthorized accesses as expected.

Comments

# SharePoint Check Out Policy Honoring | Games Money said on January 7, 2009 11:33 AM:

PingBack from http://games-money.com/blog/2009/01/07/sharepoint-check-out-policy-honoring/

# SharePoint Check Out Policy Honoring | Games Money said on January 7, 2009 11:33 AM:

PingBack from http://games-money.com/blog/2009/01/07/sharepoint-check-out-policy-honoring/

Anonymous comments are disabled