SharePoint list item attachments' size

Today, a small post about getting the size of all SharePoint list item's attachments.

Where are the attachments

All list item's attachments SharePoint stores in a folder, the path which is formed as follows:
<ListURL>/Attachments/<ListItemID>

Thus our problem reduces to obtaining the size of the files contained in this folder.

Solution

For the convenience of further application of the method can be written extension method, something like this:

  1. public static class SPListItemExtensions
  2. {
  3.     /// <summary>
  4.     /// Atachments' size
  5.     /// </summary>
  6.     /// <param name="item">List item</param>
  7.     public static long AttachmentsSize(this SPListItem item)
  8.     {
  9.         // Attachments' URL prefix
  10.         var folderUrl = item.Attachments.UrlPrefix;
  11.         // The List containig the element
  12.         var list = item.ParentList;
  13.         // The Web containing the list
  14.         var web = list.ParentWeb;
  15.         // Get the folder that contains attachments
  16.         var folder = web.GetFolder(folderUrl);
  17.         // Get all files in a folder and summarize their size
  18.         var length = folder.Files
  19.             .Cast<SPFile>()
  20.             .Sum(f => f.TotalLength);
  21.         return length;
  22.     }
  23. }

I think detailed comments for this code are not needed.

Using

Use this extension method as follows:

  1. SPListItem item = GetListItem (); // The method returns a list item
  2. var  = totalSize item.AttachmentsSize ();
Vitaly Zhukov

Vitaly Zhukov

SharePoint Architect, Developer, Technical Trainer, Microsoft MVP (Office Development). Above 15 years of total experience working with SharePoint, Dynamics CRM, Office 365, and Microsoft stack development.

You May Also Like

SharePoint 2007. The max/min value of filed in SharePoint list

SharePoint 2007. The max/min value of filed in SharePoint list

SharePoint 2010. Custom forms for ContentType

SharePoint 2010. Custom forms for ContentType

Mask "Created By" and "Modified By" user names from forms and views

Mask "Created By" and "Modified By" user names from forms and views

SharePoint 2013. Geolocation field type

SharePoint 2013. Geolocation field type

SharePoint Ribbon. Creating multi level menu

SharePoint Ribbon. Creating multi level menu