By: Matt Takhar | Updated: 2010-06-08 | Comments | Related: > SharePoint Configuration
Problem
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. You may be doing this already but still getting the error as there is a gotcha, your objects need to be instantiated inside the delegate.
This works:
Guid webGuid = web.ID; Guid siteGuid = web.Site.ID; string fileURL = item.File.Url; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(siteGuid)) { using (SPWeb ElevWeb = site.OpenWeb(webGuid)) { SPFile ElevFile = ElevWeb.GetFile(fileURL); // do something with ElevFile } } });
This fails, because the SPFile object is instantiated outside of the delegate:
Guid webGuid = web.ID; Guid siteGuid = web.Site.ID; SPFile ElevFile = item.File; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(siteGuid)) { using (SPWeb ElevWeb = site.OpenWeb(webGuid)) { // do something with ElevFile - breaks } } });
There are 2 big things to know about this:
- It runs using the App Pool account, so you must ensure that the App Pool account is a member of a site collection group with sufficient perms to to add/edit/delete or whatever your code is trying to do. If not, the code will quietly break without popping an exception
- All objects used within the delegate must be instantiated within the delegate, otherwise the elevation will fail. You can safely call scalars instantiated outside of the delegate, but not object variables like site or web.
Next Steps
- Review the MSDN method article here - RunWithElevatedPrivileges
- Review your code
- Other resource - Elevation of Privilege
About the author
This author pledges the content of this article is based on professional experience and not AI generated.
View all my tips
Article Last Updated: 2010-06-08