foreach webs access denied

Beware that when crawling "AllWebs" in a loop using the user context, the current user may not have access to all of those SPWebs. This would may throw an access denied page at the user.
Incriminated code example:
foreach(SPWeb web in SPContext.Current.Site.AllWebs)
{
  // do something to web
  web.Dispose();
}
This will throw an access denied exception when trying to instantiate the SPWeb object for a web that the current user is not allowed to browse.

Two solutions:
1) Run with elevated privileges:
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID))
  {
    foreach(SPWeb elevatedWeb in elevatedSite.AllWebs)
    {
      // do something to web
      elevatedWeb.Dispose();
    }
  }
}
2) Fetch from a collection of webs that the current user is allowed to browse.
SPWebCollection webs = SPContext.Current.Web.GetSubwebsForCurrentUser();
foreach(SPWeb web in webs)
{  
  // do something to web
  web.Dispose();
}

Ref:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.allwebs.aspx
http://msdn.microsoft.com/en-us/library/bb466220.aspx

Comments