Pages

Feb 9, 2011

Query whole site collection using SPSiteDataQuery

Using the SPQuery class you can query one SharePoint list for items.

To set up a query across a whole site collection you can use the SPSiteDataQuery object.

The following method fetches all .doc files from all doclibs of the site collection and prints out a list of urls to those items.

public void TestSiteDataQuery() {   using (SPSite site = new SPSite("http://localhost"))   {     using (SPWeb web = site.OpenWeb("/"))     {       SPSiteDataQuery query = new SPSiteDataQuery();         // Search in doclibs only       query.Lists = "";         // Only .doc files       query.Query =       @"                                     doc                    ";         // Select only needed columns: file reference       query.ViewFields = "";         // Search in all webs of the site collection       query.Webs = "";         // Perform the query       DataTable table = web.GetSiteData(query);         // Generate an absolute url for each document       foreach (DataRow row in table.Rows)       {         string relativeUrl =            row["FileRef"].ToString().Substring(             row["FileRef"].ToString().IndexOf("#") + 1);         string fullUrl = site.MakeFullUrl(relativeUrl);           // Write urls to console         Console.WriteLine(fullUrl);       }     }   } }

No comments: