Access Denied when accessing properties in SPWeb with Elevated Privileges as a visitor

I’m experiencing a strange problem when trying to access various properties and other SPWeb’s when running with Elevate Privileges and a user who is a visitor.  Here’s a snippet of code:

SPSecurity.RunWithElevatedPrivileges(delegate()  
{  
  SPWeb spWeb = SPContext.Current.Web;  
  spWeb.Site.CatchAccessDeniedException = false;  
  ListUsers(spWeb);  

I am getting an Access Denied error for visitors which is odd as RunWithElevatedPrivileges should give the code access.  It only works if the user has some higher level permissions assigned.

I have added the CatchAccessDeniedException temporarily to prevent the access denied errors halting the code.  If I examine spWeb in the debugger and drill down into the Webs to read the Name and Count properties I see this ‘spWeb.Webs.Count’ threw an exception of type ‘System.UnauthorizedAccessException’.

The ListUsers method recursively traverses the Webs in each sub-web and it is here where the code starts to fall over (on the oWeb.Webs.Count line – same exception as I see in the debugger as mentioned above).  Here’s a cut down snippet of that function…

privatevoid ListUsers(SPWeb oWeb)  
{  
try
    {  
if ( oWeb.Webs.Count > 0 )  
        {  
foreach ( SPWeb oSubWeb in oWeb.Webs )  
            {  
using ( oSubWeb )  
                {  
                    ListUsers( oSubWeb );  
// some functionality
                }  
            }  
        }  
    }  
catch (Exception)  
    {  
    }  
}  

It seems I am only able to read the properties of the current site when the user is a visitor.  A Site Owner or Member (contribute permissions etc) seem to work ok.  Have I missed something critical here or is there a problem with my installation of SharePoint?  The same occurs on our development and test servers.

You cannot use current  context inside Elevated Privileges.Create a new instance of SPWeb, SPSite siteColl = SPContext.Current.Site;SPWeb site  = SPContext.Current.Web;SPSecurity.RunWithElevatedPrivileges(delegate() {using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;string Visits = ElevatedsiteColl.Usage.Visits.ToString();string RootAuditEntries = ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString(); } }});

SPContext.Current object is created with security context of current  logged in user. So you will get access  denied error. Following code  should work:SPSite site = SPContext.Current.Site; SPWeb web = SPContext.Current.Web; SPSecurity.RunWithElevatedPrivileges(delegate() {   using (SPSite secureSite = new SPSite(site.ID)) {     using (SPWeb secureWeb= secureSite.OpenWeb(web.ID)) {      ListUSers(secureWeb);     }   } }); 

Thank you both.  The above works.