RunWithElevatedPrivileges delegate

When developing for SharePoint you may find your code does not execute due to the users permission levels.

Solution — This is a common problem when developing in SharePoint. Your code works perfectly during development as your mostly likely developing as the local admin on your “Development” SharePoint server, right? However, when you try running your code as a normal SharePoint user it doesn’t run correctly and throws a permissions error.

The solution is to make sure you elevate your code ( SPSecurity.RunWithElevatedPrivileges(..delegate here..)
) correctly where needed.

The type of the parameter of SPSecurity.RunWithElevatedPriveledges(….) is Microsoft.Sharepoint.SPSecurity.CodeToRunElevated

Add a breakpoint on the line in the same line as RunWithElevatedPriviledges, and then step into the code pressing F11.

1. Elevated Prividges runs under Application Pool ID.
2. All objects used inside the delegate must be instantiated within the delegate.

This works because all permission-based objects are created using the elevated priveledges

Also, even inside SPSecurity.RunWithElevatedPrividge(), don’t use SPContext
because it still works as a regular user.

This fails because the SPFile object is created not using the elevated prividges

Another way to do this Is using SPUserToken


Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: