Friday, February 7, 2014

Query all the documents by its file type from a Site and its all sub sites using SPSiteDataQuery


I had to develop a web part where I had to query and display all the document items which the file extensions are “docx” under a particular site collection including its sub sites. I used SPSiteDataQuery class in order to achieve.


using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                using (SPWeb spWeb = spSite.OpenWeb())
                    SPSiteDataQuery spSiteDataQuery = new SPSiteDataQuery();

                    spSiteDataQuery.Query =
         <FieldRef Name='DocIcon' />
         <Value Type='Computed'>docx</Value>
                    spSiteDataQuery.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Editor' /><FieldRef Name='ContentType' />";
                    spSiteDataQuery.Lists = "<Lists ServerTemplate='101'/>"; //Set the list template by providing its template type id

                    spSiteDataQuery.Webs = "<Webs Scope='Recursive'/>";//Recursive: Current site and any subsite
                    //Scope='SiteCollection': all webs in the current site collection

                    //Get the results into a datatable
                    DataTable resultsTable = spWeb.GetSiteData(spSiteDataQuery);

                    //Bind the results in to a asp grid view
                    GridView spGridView = new GridView();
                    spGridView.AutoGenerateColumns = true;
                    spGridView.DataSource = resultsTable;


The results will look something as below. 

I have posted the my sln file here. Please download in case if you need


No comments:

Post a Comment