SPC050201: Instantiate a new SPSite inside RunWithElevatedPrivileges

An SPSite object created outside the delegate can be referenced inside the delegate, however, the methods and property assessors of the object run with the privileges of the user context in which the objects were created, not with the elevated privileges.

TypeName: InstantiateNewSPSiteInRunWithElevatedPrivileges
CheckId: SPC050201
Severity: CriticalWarning
Type: AssemblyFileReference
Resolution

Instantiate a new SPSite inside RunWithElevatedPrivileges.

Bad Practice:

SPSite site = new SPSite("http://mysharepointsite");
SPSecurity.RunWithElevatedPrivileges(delegate()
{
  // This SPWeb will NOT have elevated privileges, because "site" does not
  SPWeb notElevatedWeb = site.RootWeb;  
});
Good Practice:
SPSite site = new SPSite("http://mysharepointsite");
// additional code using the site object
SPSecurity.RunWithElevatedPrivileges(delegate()
{
  // Create a new elevated version of the same site collection object
  using (SPSite elevatedSite = new SPSite(site.Id))     
  {
    SPWeb elevatedWeb = elevatedSite.RootWeb;
    // perform elevated operations with elevatedWeb here. . .
  } // SPSite object gets disposed automatically
});  

Links

comments powered by Disqus