Working on Attachment object SPFile in a share point list

Hi,

While working with share point, many a times, when you are working with list item you have attachments with the list item. Many a times you want to programmatically access these attachment files (as SPFile objects). The SPListItem also exposes a collection of all the Attachments with the help of the property Attachments. But this list is nothing but a collection of string containing the filename of the Attachment.

To get to work with the actual SPFile object for each attachment, this will not help much. There are two way to get the SPFile object for the attachments.

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

Next you can easily iterate through all the Files in the folder like this.

foreach (SPFile file in folder.Files)
{
        ////Work with SPFile object here.
}

Another way is to simple use the following code.

foreach (string fileName in item.Attachments)
  {
    SPFile file = item.ParentList.ParentWeb.GetFile(
      item.Attachments.UrlPrefix + fileName);

        ////Work with SPFile object here.

  }

 

Vikram


Share this post   Email it

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2012 Vikram Lakhotia