Until today I had been using the Using statement to open and dispose of webs.
The variable relative_web_url is defined by a user input in the custom web part editor.
using (SPWeb web = SPContext.Current.Site.OpenWeb(relative_web_url); {
}
What I found though was that sometimes the web opened in the using was either SPContext.Current.Web or SPContext.Current.RootWeb and that the automatic disposing of these webs as you would suspect would lead to errors in the logs.
I then conjured this method which only disposes of the web if it isn't in the SPContext.Current object.
SPWeb web = null;
try
{
web = SPContext.Current.Site.OpenWeb(relative_web_url);
}
catch (Exception exception)
{
}
finally
{
if (web != null && web.ID != SPContext.Current.Web.ID && web.ID != SPContext.Current.Site.RootWeb.ID)
web.Dispose();
}
Is this a good solution? Am I doing this all wrong? Is there a better way to open webs that may or may not be in SPContext.Current object.