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:
- public static class SPListItemExtensions
- {
- /// <summary>
- /// Atachments' size
- /// </summary>
- /// <param name="item">List item</param>
- public static long AttachmentsSize(this SPListItem item)
- {
- // Attachments' URL prefix
- var folderUrl = item.Attachments.UrlPrefix;
- // The List containig the element
- var list = item.ParentList;
- // The Web containing the list
- var web = list.ParentWeb;
- // Get the folder that contains attachments
- var folder = web.GetFolder(folderUrl);
- // Get all files in a folder and summarize their size
- var length = folder.Files
- .Cast<SPFile>()
- .Sum(f => f.TotalLength);
- return length;
- }
- }
I think detailed comments for this code are not needed.
Using
Use this extension method as follows:
- SPListItem item = GetListItem (); // The method returns a list item
- var = totalSize item.AttachmentsSize ();