Archives / 2008 / September
  • Retrieving attachment SPFile object from the Share point List Item


    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.