Wednesday, March 30, 2011

SharePoint SPSecurity.RunWithElevatedPrivileges Usage

SPSecurity.RunWithElevatedPrivileges is used to run or execute the set of code statements in the context of an Application Pool Account instead of Current Logged in User.

The below code snippet shows the implementation details.
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
web.AllowUnSafeUpdates = true;
//Code to edit/delete the file in a library
web.AllowUnsafeUpdates = false;
SPContext.Current.Web can not be used directly with in the RunWithElevatedPrivileges block as the SPWeb object becomes a instance of current logged-in user's context and it gives the below error if tries to update any content in the same Web with READ only access.

Error : Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

To address the issue, a new instance of SPSite and SPWeb should be cerated within the RunWithElevatedPrivileges code block as above.

No comments:

Post a Comment