Export (0) Print
Expand All

SPSecurity.RunWithElevatedPrivileges Method

Windows SharePoint Services 3

Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

[SharePointPermissionAttribute(SecurityAction.Demand, Impersonate = true)]
[SharePointPermissionAttribute(SecurityAction.Demand, ObjectModel = true)]
public static void RunWithElevatedPrivileges(
	SPSecurity.CodeToRunElevated secureCode
)

Parameters

secureCode
Type: Microsoft.SharePoint.SPSecurity.CodeToRunElevated
A SPSecurity.CodeToRunElevated object that represents a method that is to run with elevated rights.

The secureCode object can be created from any method that is parameterless and returns void. See SPSecurity.CodeToRunElevated.

You can also bypass using the SPSecurity.CodeToRunElevated constructor by defining and anonymous method inside the call to RunWithElevatedPrivileges. See the examples.

The first example shows RunWithElevatedPrivileges used with the SPSecurity.CodeToRunElevated constructor. In this example, GetSitesAndGroups is a parameterless method that returns void and is defined somewhere that can be accessed by the Button1_Click method.

protected void Button1_Click(object sender, EventArgs e)
{
   SPSecurity.CodeToRunElevated elevatedGetSitesAndGroups = new SPSecurity.CodeToRunElevated(GetSitesAndGroups);
   SPSecurity.RunWithElevatedPrivileges(elevatedGetSitesAndGroups);
}

The next example shows the syntax that is required to define an anonymous method in the call to RunWithElevatedPrivileges.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // implementation details omitted
});

You must create a new SPSite object inside the delegate because SPSite objects created outside do not have Full Control even when referenced inside the delegate. Use the using keyword to ensure that the object is disposed in the delegate. The next example shows this.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(web.Site.ID))
    {
    // implementation details omitted
    }
});

Community Additions

ADD
Show:
© 2014 Microsoft