In this post we will discuss about what is RunWithElevatedPrivileges and how to use RunWithElevatedPrivileges in SharePoint 2010.
You can also check my previous articles on Call jQuery to SharePoint page using Custom Action [Read here
], Create Page Layout using SharePoint Designer 2010 [Read here
] and custom timer job sharepoint 2010 [Check here
- Suppose you have written a piece of code that will add an item to a SharePoint list. But suppose a user has only read access to the site then s/he will get the access denied error when try to execute the code. But still you can run the code by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
- The SPSecurity class exposes a method called RunWithElevatedPrivileges, which gives you an option to elevate the privilege to the application pool identity under which your code is executing.
// Code will go where
- Elevated privilege can be used to bypass or work with security.
Here are some points to follow while working with RunWithElevatedPrivileges.
- Avoid using SPSecurity.RunWithElevatedPrivileges to access the SharePoint object model. Instead, use SPUserToken to impersonate SPSite with a specific account, as shown previously.
- If you do use SPSecurity.RunWithElevatedPrivileges, dispose of all objects in the delegate. Do not pass SharePoint objects out of the RunWithElevatedPrivileges method.
- Only use SPSecurity.RunWithElevatedPrivileges to make network calls under the application pool identity. Don’t use it for elevation of privilege of SharePoint objects.
If you run code with elevated privileges and you create new objects, such as list items within a list, the user automatically assigned as author or editor is SHAREPOINT\system.
Here is an example that will add an item to a SharePoint list.
using (SPSite myTopSite = new SPSite(SPContext.Current.Site.ID))
using (SPWeb myTopWeb = myTopSite.OpenWeb(SPContext.Current.Site.RootWeb.ID))
myTopWeb.AllowUnsafeUpdates = true;
SPList listMyList = myTopWeb.Lists.TryGetList("MyList");
SPListItem newItem = listMyList.Items.Add();
newItem["Title"] = "Item 1";
newItem["Description"] = "This is item 1";
myTopWeb.AllowUnsafeUpdates = false;
catch (Exception ex)