Open attachments in a list, without having to open that record

Recently, I have answered for one of the queries raised in a SharePoint forum. Copying the same here for reference.

Question:

Hi

I've created a customized list and enabled the option that makes users possible to add an attachment.
Enabling this option added automatically a new column with as "name" an icon of a paperclip.
That's fine to me, but when an attachment is added to a record, that icon als appears.

Is it a possible to change this, so the name of the attachment is listed?
Is it possible to add the location of the attachment (hyperlink) to that name.

I don't find it very userfriendly that the users can't see what the attachment is handling about.
I would like that they don't have to open each record to find out.

Thx for help

Best Regards

Tom

My Answer:

Hi Tom

This can be achived with the following steps.

1. In your custom list, create a new Hyperlink column with the name 'Attachment' and add it to the view as you wish.

2. Creata a simple Console Application and write the following code.

SPSite site = new SPSite([URL of your site]);
SPWeb web = site.OpenWeb();
SPList list = web.Lists[[Display Name of your list]];

           
for (int i = 0; i < list.Items.Count; i++)
{
   SPListItem item = list.Items[i];

   
   if (item.Attachments.Count > 0)
   {
      string attachmentURL = item.Attachments[0];
      item["Attachment"] = item.Attachments.UrlPrefix +  attachmentURL + ", " + attachmentURL;
      

      item.Update();
    }
}

3. Execute the code and see the result in the list.

Note: This solution assumes that you are adding only one attachment per list item. If you want to use it for multiple attachments, you may need to try a different approach.

Thanks
Bala

No comments: