Saturday, January 28, 2012

Sharepoint - Loop through all site collections of a webapplication

Here is the code....

try
            {
                string webapplicationUrl = "http://webapplicationURL/";

                SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(webapplicationUrl));
                SPSiteCollection siteCollections = webApplication.Sites;

                foreach (SPSite siteCollection in siteCollections)
                {
                    Console.WriteLine("SiteCollection URL:" + siteCollection.Url);

                    using (SPSite oSiteCollection = new SPSite(siteCollection.Url))
                    {
                        SPWebCollection collWebsites = oSiteCollection.AllWebs;
                        foreach (SPWeb oWebsite in collWebsites)
                        {
                            Console.WriteLine("Website URL: " + oWebsite.Url);
                            oWebsite.Dispose();
                        }
                    }
                }
                Console.WriteLine("---------Program Completed Successfully. Please click enter to exit.------ ");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR:" + e.Message);
                Console.WriteLine("---------ERROR: Program terminated because of ERROR. Please click enter to exit.------ ");
                Console.ReadLine();
            }

No comments:

Post a Comment