tags:

views:

156

answers:

1

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();

        }

    }

}
+1  A: 

Figured it out! Instead of this.Web.Groups, it is just web.Groups... I wasn't using the right object.

Josh