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

Tech Lead, Architect, Developer, Technical Trainer, Microsoft MVP. Over 20 years of experience in system integration and software development. I specialize in designing and implementing scalable, high-performance software solutions across various industries.

You May Also Like

Collect SharePoint telemetry with Azure Application Insights. Part I. Server-Side

Collect SharePoint telemetry with Azure Application Insights. Part I. Server-Side

SharePoint New Team Site. Inside Out

SharePoint New Team Site. Inside Out

SharePoint 2019 Preview

SharePoint 2019 Preview

SharePoint Ribbon. Creating multi level menu

SharePoint Ribbon. Creating multi level menu

SharePoint 2013. Geolocation field type

SharePoint 2013. Geolocation field type

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 2010. Custom forms for ContentType

SharePoint 2010. Custom forms for ContentType

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

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