Basic operations with SPListItem.Attachments

Intro

Recently I have worked on a small SharePoint onprem project and a customer wanted a custom List View/Edit forms for one of the lists. Long story short - they wanted a custom control to manage attachments.

Code

SPListItem has a property for this SPListItem.Attachments

After googling for awhile I have found enough info to make everything work.

There are few things to remember about this collection:

SPAttachmentCollection contains strings instead of objects. So, it is possible to get a list of attached file names like this:

var fileNames = listItem.Attachments
    .Cast<string>()
    .ToList();

It is easy to get the url to given attachment:

var url = SPUrlUtility.CombineUrl(listItem.Attachments.UrlPrefix, fileName)

Also, you can get SPFile using the attachment url:

var web = listItem.ParentList.ParentWeb;
var file = web.GetFile(url);

It is easy to add a new attachment:

SPList item = list.AddItem();
listItem.Attachments.Add(fileName, fileBytes);
item.Update();

It is also possible to add an attachment with no call to the item.Update method:

listItem.Attachments.AddNow(fileName, fileBytes);

AddNow, DeleteNow and RecycleNow will do the job immediately.

Summary

Sometimes it is hard to understand why SharePoint works this way. SPAttachmentCollection is a nice example of how confusing SharePoint can be. You expect to get something like SPAttachment from the collection, but no - you will get a string.

More info: