Archive for the ‘SharePoint’ Category

Take the following code snippet:

SPAttachmentCollection attachments = item.Attachments ;

What exactly is SPAttachmentCollection a collection of? Most collections tell you what they’re a collection of…. but remember the golden rule of SharePoint – that’s right, if its possible to break, its already broken.

In case you’re wondering an SPAttachment object does not exist?

Each item in a SharePoint list has an associated SPAttachmentCollection array. It would seem logical that this array would function like most of the other object arrays in SharePoint and be comprised of SPAttachment or, more likely, SPFile objects so we could do the following:

SPAttachmentCollection attachments = listitem.Attachments;
foreach (SPFile file in attachments)
{
// Do something
}

As doing that throws an invalid cast exception. Surprised? Because

“The SPAttachmentCollection is simply an array of strings representing the file name of each attachment”

Also several useful methods associated with the SPAttachmentCollection, like Add(), Delete(), and Recycle()

Here is two metnods to get Attachments as SPFile

Method 1:

SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[listitem.ID.ToString()];

Then you can do:

foreach (SPFile file in folder.Files)
{
// Something useful here
}

Method 2:

SPAttachmentCollection attachments = listitem.Attachments;
foreach (string fileName in attachments)
{
SPFile file = web.GetFile(attachments.UrlPrefix + fileName);
// Do something ...
}