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

Matt has a background in engineering and has 15+ years of IT experience. He has been working with SharePoint since 2006. In 2007 he attended a 6 day SharePoint boot camp by Firebrand training. He aced the WSS 3.0 and MOSS 2007 exams and this makes him a Microsoft Technical Specialist in Windows SharePoint Services Configuration and a Microsoft Technical Specialist in Microsoft Office SharePoint Server Configuration. Since 2007 he has been specializing in delivering SharePoint solutions and in 2009 he changed roles to Software Development Manager, where his team specializes in developing SharePoint based solutions.