Michael A
Michael A

Reputation: 9910

Is it possible to get a list of site collections of a SharePoint server?

I'm trying to get a full output of the list of site collections on a SharePoint Server so I can enumerate through them and collect data. I found the following code:

foreach (SPWebApplication wa in SPWebService.ContentService.WebApplications)
{
    foreach (SPSite sc in wa.Sites)
    {
        try
        {
            Console.WriteLine("Do something with site at: {0}", sc.Url);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception occured: {0}\r\n{1}", e.Message, e.StackTrace);
        }
        finally
        {
            sc.Dispose();
        }
    }
}

But unfortunately this throws the following error:

System.NullReferenceException: Object reference not set to an instance of an object.

Is there a possible way of doing this or will I have to supply the server name (even though I'm running this code directly on the SharePoint server?)

Upvotes: 0

Views: 2234

Answers (1)

roqz
roqz

Reputation: 1018

I think SPWebservice.ContentService does not give you all services and therfore not all WebApps, this code just runs fine for me:

SPServiceCollection services = SPFarm.Local.Services;
        foreach(SPService curService in services)
        {
            if(curService is SPWebService)
            {
                SPWebService webService = (SPWebService)curService;


                foreach(SPWebApplication webApp in webService.WebApplications)
                {
                    foreach(SPSite sc in webApp.Sites)
                    {
                        try
                        {
                            Console.WriteLine("Do something with site at: {0}", sc.Url);
                        }
                        catch(Exception e)
                        {
                            Console.WriteLine("Exception occured: {0}\r\n{1}", e.Message, e.StackTrace);
                        }
                    }
                }
            }
        }

Upvotes: 3

Related Questions