SharePoint Document Counter Counts The Document Downloads

In this post I’m going to show you how to count the document events of SharePoint site, after going through this post you will learn how to count the document downloads, views, updates, deletion, restoration etc.

I remember this solution has been asked by few people on this blog.

Before knowing the document events (add, delete, update, view etc) we have to configure the audit entry settings for the SharePoint site collection in site settings page under Site Collection Administration section (see figure 1)

Figure 1 - Configure Site Collection Audit Settings

Figure 1 – Configure Site Collection Audit Settings

On Audit Settings page check the required events to track, in this example I’m configuring for Opening or downloading documents, viewing items in lists, or viewing item properties, Editing items, Deleting or restoring items

Figure 2 - Configure Audit Events

Figure 2 – Configure Audit Events

You can also configure audit entry settings programmatically with few lines of code, here it is:

static void Main()
            using (SPSite mySite = new SPSite("http://<servername>:port"))
                using (SPWeb myWeb = mySite.OpenWeb())
                    mySite.Audit.AuditFlags = SPAuditMaskType.All; //Configures all settings

                    //you can even configure specific settings using the below lines of code

                    //mySite.Audit.AuditFlags = SPAuditMaskType.CheckIn | SPAuditMaskType.CheckOut | SPAuditMaskType.ChildDelete |
                    //     SPAuditMaskType.Copy | SPAuditMaskType.Delete | SPAuditMaskType.Move | SPAuditMaskType.ProfileChange |
                    //     SPAuditMaskType.SchemaChange | SPAuditMaskType.Search | SPAuditMaskType.SecurityChange |
                    //     SPAuditMaskType.Undelete | SPAuditMaskType.Update | SPAuditMaskType.View | SPAuditMaskType.Workflow;

                    //mySite.Audit.AuditFlags = SPAuditMaskType.None; //Configures to none

            Console.WriteLine("Press any key to continue.....");

After configuring the settings, SharePoint audits the library events on item viewing, downloading, editing, deleting etc.,
SharePoint also generates audit log reports on this events in .CSV format. In this example we are reading the data from the configured audit entry logs to know event actions on documents.

Use the below code to know the event count on documents

using System;
using System.ComponentModel;
using System.Web;
using System.Text;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace DownloadCounter.VisualWebPart1
    public class VisualWebPart1 : WebPart
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/DownloadCounter/DownloadCounterWebPart/DownloadCounterUserControl.ascx";
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();
        string errorMessage = string.Empty;

        protected override void CreateChildControls()
            Control control = Page.LoadControl(_ascxPath);


            myGridView = new SPGridView();
            myGridView.AutoGenerateColumns = false;
            myGridView.Enabled = true;
            myGridView.AllowSorting = true;
            myGridView.AllowGrouping = true;
            myGridView.AllowGroupCollapse = true;
            myGridView.GroupField = "Event";
            myGridView.DisplayGroupFieldName = false;
            myGridView.AllowPaging = true;
            myGridView.PageSize = 50;
            myGridView.PageIndexChanging += new GridViewPageEventHandler(myGridView_PageIndexChanging);

            BoundField colEvent = new BoundField();
            colEvent.DataField = "Event";
            colEvent.HeaderText = "Event";

            BoundField colItemType = new BoundField();
            colItemType.DataField = "ItemType";
            colItemType.HeaderText = "ItemType";

            BoundField colDocLocation = new BoundField();
            colDocLocation.DataField = "DocLocation";
            colDocLocation.HeaderText = "DocLocation";

            BoundField colOccurred = new BoundField();
            colOccurred.DataField = "Occurred";
            colOccurred.HeaderText = "Occurred";

            BoundField colUserName = new BoundField();
            colUserName.DataField = "UserName";
            colUserName.HeaderText = "UserName";

            myGridView.PagerTemplate = null;
        private void GroupByGridView()
            StringBuilder scriptFunction = new StringBuilder();
            scriptFunction.Append("<script src='/SiteAssets/jquery-1.4.2.min.js' type='text/javascript'></script>");
            scriptFunction.Append("<script type='text/javascript'>");
            scriptFunction.Append("$(document).ready(function(){$('.ms-gb').each(function(){var rowNums=$(this).nextUntil('.ms-gb').length;");
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "GroupBy", scriptFunction.ToString());

        private void GetAudEntries()
                SPSite mySite = SPContext.Current.Site;
                SPWeb myWeb = SPContext.Current.Web;
                DataTable myDataTable = new DataTable();
                DataRow myRow;
                SPUser user;
                    SPAuditQuery wssQuery = new SPAuditQuery(mySite);
                    SPAuditEntryCollection auditCol = mySite.Audit.GetEntries(wssQuery);

                    myDataTable.Columns.Add("Occurred", typeof(DateTime));

                    foreach (SPAuditEntry entry in auditCol)
                        if (entry.DocLocation.EndsWith(".xls") || (entry.DocLocation.EndsWith(".doc")) || (entry.DocLocation.EndsWith(".ppt")))
                            user = myWeb.SiteUsers.GetByID(entry.UserId);
                            myRow = myDataTable.NewRow();
                            myRow["Event"] = entry.Event;
                            myRow["ItemType"] = entry.ItemType.ToString();
                            myRow["DocLocation"] = entry.DocLocation;
                            myRow["Occurred"] = entry.Occurred.ToLocalTime();
                            myRow["UserName"] = user.ToString();
                    myGridView.DataSource = myDataTable;
                catch (Exception ex)
                    errorMessage = ex.ToString();

        void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
            myGridView.PageIndex = e.NewPageIndex;

        protected override void RenderContents(HtmlTextWriter writer)

Use the above code or try to deploy the DownloadCounter.wsp
Note: In the above code we have used JQuery jquery-1.4.2.min.js files to show the count of the group by field, so please download the jquery-1.4.2.min.js file from and place in some location of the SharePoint site and also refer the same source location in the above code, in this example I have placed the Jquery file in Site Assets library, you can even place in the same location if you don’t want to change the code.

After deploying the downloaded solution, please try to activate Download Counter Feature see figure 3

Figure 3 - Activate Download Counter Feature

Figure 3 – Activate Download Counter Feature

Then add the webpart to the page see figure 4

Figure 4 - Adding Download Counter WebPart to SharePoint Site

Figure 4 – Adding Download Counter WebPart to SharePoint Site

Then you can view the webpart updating on every action of documents see figure 5

Figure 5 - Download counter webPart shows the count of events for the documents

Figure 5 – Download counter webPart shows the count of events for the documents

9 Responses to “SharePoint Document Counter Counts The Document Downloads”

  1. Hi ,

    I have downloaded the “Download Counter Webpart”, but when I am trying to add it on the site its telling that its an invalid webpart and to check if its .webpart or .dwp file. Since I am looking to have count on number of times the document is downloaded could you please help me in getting a new webpart.

  2. Just tried to install your webpart. Well, it doesn’t work (for me). It sais:

    “There are no items to show in this view.”

    I enabled auditing with the given steps.

  3. Hi i read this article and this is very useful to me but i cant found Download Counter Feature in site collection feature
    and also one more thing this is for document now i want to get track of Share point list item (how many time list item view ?) so can u provide me any reference to get this track value….


  4. Hi,

    this is helpful .
    my issue is below

    how to get list item audit track in web part like (how many time list item view by users i want total view count) ??


  5. Hi, This will work on SP 2007?

  6. nice article but how to get the download count.

  7. Hi,
    I have used your code and i get the Audits for particular site or list that’s fine. But i want to display the current logged user documents audits only. Example: if i have two users named with User1 and User 2
    If User1 logged into site, then his document audits only should display to him which are viewed or updated by another User like User2.
    I hope you understood what i need.
    Please help me

  8. Please notice that this WebPart only tracks the following extensions .xls .doc and .ppt

  9. NIce article, but i need to get the document count added in last 5 days.
    is there is any way

Leave a Reply