Printer Friendly Version      Send     
Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Server Technologies
SDK Documentation
SPSecurity Class
SPSecurity Methods
 RunWithElevatedPrivileges Method
SPSecurity.RunWithElevatedPrivileges Method (Microsoft.SharePoint)
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)
Visual Basic (Declaration)
<SharePointPermissionAttribute(SecurityAction.Demand, Impersonate:=True)> _
<SharePointPermissionAttribute(SecurityAction.Demand, ObjectModel:=True)> _
Public Shared Sub RunWithElevatedPrivileges ( _
    secureCode As CodeToRunElevated _
)
Visual Basic (Usage)
Dim secureCode As CodeToRunElevated

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

Parameters

secureCode

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
    }
});
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker