Add a user to Sharepoint site using Elevated priviledges to avoid "Access denied Error" 

To add a user to a SharePoint site in order to avoid "Access Denied" error, or for cases when some high level operations needs to be performed by the person with "Member" access, use the below code.

string strUserLogin = "mylogin";
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
   using (SPSite elevatedSite = new SPSite(web.Site.ID))
   {
        elevatedSite.AllowUnsafeUpdates = true;
        SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
        {
                elevatedWeb.AllowUnsafeUpdates = true;
                SPUser user = elevatedWeb.EnsureUser(strUserLogin);
         }
     }
  }

Leave your comments below.

No comments: