RepDetec
RepDetec

Reputation: 751

SharePoint 2010: Adding a User to a Group from code

I am trying to add a user to an existing group from a custom login page. Right now, I have no problem getting the current user from SPWeb.CurrentUser. I can view all of this current users groups, but now I am having a problem adding this user to an existing group. I think I need to use SPRoleDefinition and SPRoleAssignment, but all I can find is how to change the permissions on a group using these classes. Does anyone know how I can add this user to a group by the groupname?

Thanks!

Upvotes: 2

Views: 3300

Answers (3)

ashish.chotalia
ashish.chotalia

Reputation: 3746

You can utilize this function to add user to the current site. You need to pass Group name and UserName.

public void AddUsers(string groupname, string username)
{
   try
   {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
               // Gets a new security context using SHAREPOINT\system
               using (SPSite site = new SPSite(SPContext.Current.Site.Url))
               {
                     using (SPWeb thisWeb = site.OpenWeb())
                     {
                          thisWeb.AllowUnsafeUpdates = true;
                          SPUser Name = thisWeb.EnsureUser(username);
                          thisWeb.Groups[groupname].AddUser(Name);
                          thisWeb.AllowUnsafeUpdates = false;
                     }
                }
   });

  }

  catch (Exception ex)
   {
       //Log error here.
   }
}

Upvotes: 3

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

If you're trying to add a user to a group, this should work:

SPUser currentUser = SPContext.Current.Web.CurrentUser;
SPGroup group = SPContext.Current.Web.SiteGroups["My Group Name"];
group.AddUser(currentUser);

http://msdn.microsoft.com/en-us/library/ms454048.aspx

Upvotes: 1

Silx
Silx

Reputation: 2701

Have you tried any of this?

Upvotes: 1

Related Questions