In this article we explore how to retrieve all the documents in a Site Collection programmatically. The scenario is useful for applying other activities to all documents in a Site Collection.
Our Aim
Our ultimate intent is to retrieve all the document file names along with the sizes as shown below:
Server Object Model
The following are the Server Object Model types and properties we have used:
- SPSite
- SPWeb
- SPSite > AllWebs
- SPWeb > Lists
- SPList
- SPList > IsApplicationList
Web Part
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 the AllWebs property. For each Web Site (SPWeb) the corresponding lists are iterated.
The list is checked for Application List using the property IsApplicationList. This is to discard the system lists of the web site.
Code
The following is the code that performs the following activities:
- Enumerate All Web Sites in Site Collection
- Enumerate All Lists in each Web Site
- Validate that the List is Document Library
- Validate the List is Application List
- Ensures List contains Items
On the button click place the following code:
protected void GetInfoButton_Click(object sender, EventArgs e)
{
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;
}
builder.Append("</br>");
}
}
}
}
}
int itotal = (int)total / (1024 * 1000);
builder.Append("<h2> Total Size: " + itotal.ToString() + " MB</h2>");
ResultLabel.Text += builder.ToString();
}
Please note that the preceding code include the HTML formatting code as well.
Deployment
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 will see the results.
References
http://tinyurl.com/sp2010-enumdocs1
http://tinyurl.com/sp2010-enumdocs2
Summary
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.