Expand Minimize

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.

CheckId SPC050201
TypeName InstantiateNewSPSiteInRunWithElevatedPrivileges
Severity CriticalWarning
Type Assembly

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
});  

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("SPCAF.Rules.BestPracticesGroup", "SPC050201:InstantiateNewSPSiteInRunWithElevatedPrivileges", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of RENCORE AB. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.