0

I have these lines of code:

string siteUrl = "http://myTestSite";
using (SPSite siteCollectionParent = new SPSite(strUrl))
{
    SPWebApplication webApplication = siteCollectionParent.WebApplication;
    SPSiteCollection childCollections = webApp.Sites;
    foreach(SPSite siteCollectionChild in childCollections)
    {
        try
        {
            System.Console.Writeline(siteCollectionChild.Url);
        }
        finally
        {
            //Add here some code
        }
    }
}

I want to dispose the SPSite object. Which is the best solution to dispose it? Adding siteCollectionChild.Dispose() , adding childCollections.Dispose() or siteCollectionParent is disposed by garbage collection?

1
  • Are apps capable of running the server object model? I thought you had to use CSOM with apps.
    – wjervis
    May 23, 2016 at 12:04

2 Answers 2

1

If you write:

using (SPSite siteCollectionParent = new SPSite(strUrl))

you don't need to dispose because the using-Method will do this for you as you guessed. But this has no impact on your child-Instances! So for disposing your siteCollectionChild you can write

 foreach(SPSite siteCollectionChild in childCollections)
    {
        try
        {
            System.Console.Writeline(siteCollectionChild.Url);
        }
        finally
        {
            siteCollectionChild.Dispose();
        }
    }
0

If you dispose SPSite siteCollectionParent it will dispose only site collection with url strUrl. ie. only 1 site collection

And disposing childCollections or every single siteCollectionChild is similar. just you are disposing in a go if you dispose childCollections.

NOTE: You are disposinig every single SPSite in the web application.

Be careful about requirement and decide which one you want to dispose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.