SharePoint Tip #10: Using RunWithElevatedPrivileges()

When developing SharePoint (MOSS or WSS) componentes, you might have to write code that some users won't have permissions to execute. For instance, if an event handler associated with a list needs to access an item of another list, and the user that caused the event to be fired has no permissions to access it, SharePoint will throw an access denied exception. 

The solution to this kind of problems is the RunWithElevatedPrivileges of the SPSecurity class (included in the assembly Microsoft.SharePoint.dll). This method allows the execution of code as the application pool identity account and, for that reason, should be used with caution. 

Example
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // begin code to be executed with app pool account
    SPSite site = new SPSite("http://server/site");
    SPWeb web = site.OpenWeb();

    SPList
lista = web.Lists["ListaAdmin"];

    web.Dispose();
    site.Dispose();
    // end of code to be executed with app pool account
}

Attention: I placed the creation of the SPSite object inside the elevated privilege zone on purpose. The reason for this is that, if the SPSite object is created outside this zone (when the user still has its original permissions) all the actions that are executed on SPWeb or SPList objects obtained from that SPSite object, even if inside the privileged zone, will use the original permissions of the user. So, it is mandatory that the creation of SPSite objects (and similars) is placed inside the elevated privilege code block.