How to add a user to a SharePoint group programatically - Access is Denied
Posted
by Josh
on Stack Overflow
See other posts from Stack Overflow
or by Josh
Published on 2010-06-18T02:05:29Z
Indexed on
2010/06/18
2:13 UTC
Read the original article
Hit count: 399
sharepoint
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 has worked for some people). Can some help explain to me why the following does not work and still gives me an Access is Denied error?
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPControl.GetContextSite(HttpContext.Current).Url)) //have also tried passing in the ID - doesn't make a difference
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
// add user to group
SPGroup group = this.Web.Groups[groupList.Items[i].Value];
SPUser spUser = web.EnsureUser(provider + ":" + user.UserName); //provider is previously defined
spUser.Email = user.Email;
spUser.Name = txtFullName.Text;
group.AddUser(spUser);
// update
group.Update();
}
}
}
© Stack Overflow or respective owner