While programming in SharePoint, did you ever needed to work your way back to the parent website?
Probably the easiest, but not the recommended, way to do this is:
SPWeb web = SPContext.Current.Web;
while (web != null)
{
// Do your code here
web = web.ParentWeb;
}
The problem with this approach is that you are not disposing your SPWeb and SPSite objects. You should correctly dispose you SharePoint objects to avoid memory leaks in your SharePoint customizations.
A better approach that disposes all the objects correctly is this:
private void SomeMethod()
{
SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);
IterateThroughParentsAndStoreInfo(web);
web.Dispose();
site.Dispose();
}
private void IterateThroughParentsAndStoreInfo(SPWeb web)
{
// Do your code for the 'web' variable here.
if (web.ParentWeb != null)
{
using (SPWeb parentweb = web.ParentWeb)
{
IterateThroughParentsAndStoreInfo(parentweb);
}
}
}
Best practices in SharePoint programing dictate that you have to dispose your SharePoint objects. You can download the free tool SPDisposeCheck that integrates in your Visual Studio and checks if you properly disposed your objects. If not it will give you errors like:
‘Disposable type not disposed: Microsoft.SharePoint.SPWeb’
More information about disposing your objects can be found here.
Hope it helps.





Thanks, W0ut. This was a lifesaver. Needed to get the title attribute for the root site (not site collection root) and used this with a little modification: http://devharbor.blogspot.com/2011/10/sharepoint-get-parent-site-title.html
I would recommend wrapping the statement in a try/catch/finally, where you call the web and site .dipose lines in the finally block, doing a null check on each before.