SharePoint 2010 AllWebs SecurityException

I recently came across an issue with AllWebs that threw a SecurityException in certain environments and needed a way to traverse all subsites to locate based on a specific match. This is a simplified version of the solution I came up with, I hope it helps someone else out:

string title = "MySiteTitle";
Guid siteId = SPContext.Current.Site.ID;
 
using (SPSite site = new SPSite(siteId))
{
    SPWeb web = GetSubWeb(site.OpenWeb(), title);
 
    if (web != null)
    {
        // Do Stuff
    }
}


private static SPWeb GetSubWeb(SPWeb root, string title)
{
    SPWeb foundWeb = null;
 
    SPWebCollection subWebs = root.GetSubwebsForCurrentUser();
 
    foreach (SPWeb web in subWebs)
    {
        if (web.Title == title)
        {
            foundWeb = web;
            break;
        }
        else
        {
            foundWeb = GetSubWeb(web, webId);
            if (foundWeb != null)
            {
                break;
            }
        }
    }
 
    return foundWeb;
}

Leave a Reply

Your email address will not be published. Required fields are marked *