We can get the subsites under the site using CSOM easily but if we need to get all the site collections under a specific web application from a SharePoint farm, then we can’t get it directly. For that, we have to use SharePoint search. By using SharePoint Search, we set the “KeywordQuery” to filter and get the site collections. Before using the code block, we should ensure that the SharePoint Search Service Application is running and active.
The code block for this is mentioned below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.SharePoint.Client;
- using Microsoft.SharePoint.Client.Search.Query;
- namespace GetSitecollFromWebApplication {
- class GetSitecollByUsingSearch {
- static void Main(string[] args) {
- string webAppUrl = string.Empty;
- string username = string.Empty;
- string password = string.Empty;
- NetworkCredential credentials = null;
- webAppUrl = "webAppUrl";
- username = "userName";
- password = "******";
- ClientContext ctx = new ClientContext(webAppUrl);
- credentials = new NetworkCredential(username, password);
- ctx.Credentials = credentials;
-
- KeywordQuery keyQuery = new KeywordQuery(ctx);
- keyQuery.QueryText = "contentclass:\"STS_Site\"";
- keyQuery.RowLimit = 500;
- keyQuery.EnableStemming = true;
- keyQuery.TrimDuplicates = false;
- SearchExecutor searchExe = new SearchExecutor(ctx);
- ClientResult < ResultTableCollection > resultTabColl = searchExe.ExecuteQuery(keyQuery);
- ctx.ExecuteQuery();
- var siteCollection = resultTabColl.Value.SelectMany(rs => rs.ResultRows.Select(r => r["Path"])).ToList();
- if (siteCollection != null && siteCollection.Count > 0) {
- foreach(var site in siteCollection) {
- Console.WriteLine(site);
- }
- Console.ReadLine();
- } else {
- Console.WriteLine("Sorry, there were no Site Collections for the Web Application.");
- Console.ReadLine();
- }
- }
- }
- }
In this blog, I have explained how you can get all the site Collections under a SharePoint web application. I hope this blog will help you out in a few scenarios.