Category: Libraries

Getting a list item’s attachments through code

By , August 10, 2009

So, I came across the requirement to create a list of links to all of the attachments of a list item in my custom aspx page. Seems easy right? I should be able to grab the list item and do something like item.Attachments to get a collection of some kind of SPAttachment Object… right? Well as it turns out, it’s not quite so simple.

SPListItem.Attachments returns a SPAttachmentCollection object which is fairly limited in what it allows you to do.  It does provide a simple way of adding and deleting attachments, but thats about it.  You can however treat the SPAttachmentCollection as if it was a StringCollection and enumerate through the collection as shown below to get the names of the files.

1
2
3
4
5
// item is a SPListItem
foreach (string attachmentName in item.Attachments)
{
     // attachmentName is the name of the attachment
}

Well that is better than nothing, but I needed links to the documents, not just a list of them. So the next thing we need to do is prefix the attachmentName string with the rest of the URL. It turns out that it is fairly simple to use a SPFolder object as seen below to grab the rest of the URL.

1
2
3
4
5
6
// item is a SPListItem, _Files is the Literal in my custom page
foreach (string attachmentName in item.Attachments)
{
     SPFolder attachments = item.ParentList.RootFolder.SubFolders["Attachments"].SubFolders[item.ID.ToString()];                                    
     _Files.Text += "<a href=\"https://SharePoint.com/" + attachments.Url + "/" + attachmentName + "\">" + attachmentName + "</a><br>";                              
}

So, while I don’t really like it, I think this is the easiest way of getting a link to the attachments for a given list item. If anyone has a better method, please feel free to share. Below is a little image of what resulting page may look like.

ListItemAttachments