My new blog

My blog has moved to www.davehunter.co.uk/blog see you there.

Wednesday, 18 July 2007

SharePoint 2007 Running SPSecurity.RunWithElevatedPrivileges

In SharePoint Portal Server 2003 you may have needed to impersonate a user with higher priveledges than the current user executing the code. You did this using WindowsIdentity.Impersonate() method. In SharePoint 2007 and WSS V3 you have SPSecurity.RunWithElevatedPrivileges call. The code looks like:

SPSecurity.RunWithElevatedPrivileges(delegate() {

// put your code here. any code within these curly brackets will run with SharePoint system rights

});
For more information see SPSecurity.RunWithElevatedPrivileges Method on MSDN.

Please note: If you use the SPControl.GetContextSite(this.Context) within the SPSecurity.RunWithElevatedPrivileges call or have an variable defined before the call this will use the current user's rights and not the system's. For example:

SPSecurity.RunWithElevatedPrivileges(delegate() {

using (SPSite site = SPControl.GetContextSite(this.Context))
{

// site will be based on the current user that executes this code

}


});

You should use:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(web.Site.ID))
{


// site will be based on the rights for the system account

}

});
 

No comments: