RunWithElevatedPrivileges

Introduction:

In this article I am going to explain you that How to use RunWithElevatedPrivileges in sharepoint object model.
RunWithElevatedPrivileges
Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.The next example shows the syntax that is required to define an anonymous method in the call to RunWithElevatedPrivileges.

1
2
3
4
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // implementation details omitted
});


Detail
:-

The RunWithElevatedPrivileges method accepts a delegate parameter that adds a reference to a method that contains the code that is to be executed with elevated privileges.

1
2
3
4
5
6
7
8
9
10
11
12
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
      string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
      string Visits = ElevatedsiteColl.Usage.Visits.ToString();
      string RootAuditEntries =
          ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
    }
  }
});


Must read it:

In RunWithElevatedPrivileges you must then create an instance of the SPSite class and the SPWeb class. You cannot use the objects available through the Microsoft.SharePoint.SPContext.Current property. That is because those objects were created in the security context of the current user.

References:-

http://msdn.microsoft.com/en-us/library/bb466220%28v=office.12%29.aspx
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

Thanks!
Avinash

calendarMarch 26, 2012 · cardInfoyen · comments2 Comments
tagTags: , , , ,  · Posted in: MOSS, Security, SharePoint

2 Responses

  1. Sasi Kumar Reddy - November 30, 2012

    Best examples. Thanks.

  2. Sasi Kumar Reddy - November 30, 2012

    Best article to know all ways of using RuWithElevatedPrivileges.

Leave a Reply

Spam Protection: , required

myworldmaps infoyen