HELLO
MY NAME IS
JOSH RACHNER
&
I'M A TECHNOLOGIST

← Back to posts

How to add a user to a SharePoint group programatically without Access is Denied error?

19 Jun 2010 - No Comments

I have tried and tried to add a user to a SharePoint group using C# programatically (using a non-site admin). If I am logged in as a site admin, it works fine… but, if I am logged in as a non-site admin then I get an access is denied error. After doing some investigation I found that I needed to either “impersonate” the user (which didn’t seem to work) or “ensure the user”, so I have ended up at this code (which seems to work fine):

SPSecurity.RunWithElevatedPrivileges(delegate() {     using (SPSite site = new SPSite(SPControl.GetContextSite(HttpContext.Current).Url))     {         using (SPWeb web = site.OpenWeb())         {                 web.AllowUnsafeUpdates = true; // add user to sp                 SPUser spUser = web.EnsureUser(provider + ":" + user.UserName);                 spUser.Email = user.Email;                 spUser.Name = txtFullName.Text; spUser.Update(); // find sp group and add user to it                 SPGroup group = this.Web.Groups[groupList.Items[i].Value];                group.AddUser(spUser); group.Update();         }     } }

 

Here’s a couple good resources:
- http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/8793a1da-de67-45cb-9dfb-8e81fc536336
- http://blogs.devhorizon.com/reza/?p=472

Leave a Comment