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 ();

Share

Comments