In this article we can explore how to retrieve all the documents in a Site Collection programmatically. The scenario is useful to apply other activities to all documents in a Site Collection.
Our final aim is to retrieve all the document file names along with the sizes as shown below:
Server Object Model
Following are the Server Object Model types and properties we have used:
3. SPSite > AllWebs
4. SPWeb > Lists
6. SPList > IsApplicationList
Open Visual Studio 2010, create a new Visual Web Part project and place a button on it.
On click of the button the Current Site Collection is examined for all the sub sites using AllWebs property. For each of the Web Site (SPWeb) the corresponding Lists are iterated.
The list is checked for Application List using the property IsApplicationList. This is in order to discard the system lists of web site.
Following is the code that performs the following activities:
· Enumerate All Web Sites in Site Collection
· Enumerate All Lists in each Web Site
· Validate the List is Document Library
· Validate the List is Application List
· Ensures List contains Items
On the button click place the following code.
ResultLabel.Text = string.Empty;
StringBuilder builder = new StringBuilder();
double total = 0;
foreach (SPWeb web in SPContext.Current.Site.AllWebs)
foreach (SPList list in web.Lists)
if (list is SPDocumentLibrary)
if ((!list.IsApplicationList) && (list.OnQuickLaunch))
if (list.Items.Count > 0)
// Display Library Name
builder.Append("<h2>" + web.Title + " > " + list.Title + "</h2></br>");
foreach (SPListItem item in list.Items)
// Display File Name
builder.Append(item.File.Name + " (" + (item.File.Length / 1024).ToString() + " KB) </br>");
total += item.File.Length;
int itotal = (int)total / (1024 * 1000);
builder.Append("<h2> Total Size: " + itotal.ToString() + " MB</h2>");
ResultLabel.Text += builder.ToString();
Please note that the above code include the HTML formatting code as well.
Deploy the project to SharePoint and add the Web Part to a site page.
Add some documents to the current site libraries as well as in the sub sites libraries.
Try clicking the button and you can see the results.
In this article we have seen how to retrieve all documents in a Site. The same code can be extended to retrieve all documents in the Site Collection.
The source code contains the example we discussed.