1

I want to add an user to a sharepoint group.

I have the function:

    public static void AddUserInGroup(SPUser user, SPGroup group)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
                group.AddUser(user);
        });
    }

group and user are valid.

I don't understand why that code isn't working. What's the reason that SPGroup.AddUser mehod can failed ?

I already have

using(SPSite site = new SPSite(SPContext.Current.Site.ID)
using (SPWeb oWebsite = site.OpenWeb())

before my function

System.Threading.ThreadAbortException: Le thread a été abandonné. à System.Threading.Thread.AbortInternal() à System.Threading.Thread.Abort(Object stateInfo) à System.Web.HttpResponse.AbortCurrentThread() à Microsoft.SharePoint.Utilities.SPUtility.Redirect(String url, SPRedirectFlags flags, HttpContext context, String queryString) à Microsoft.SharePoint.Utilities.SPUtility.RedirectToAccessDeniedPage(HttpContext context) à Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(HttpContext context) à Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception ex) à Microsoft.SharePoint.Library.SPRequest.UpdateMembers(String bstrUrl, UInt32 dwObjectType, String bstrObjId, Guid& pguidScopeId, Int32 lGroupID, Int32 lGroupOwnerId, Object& pvarArrayAdd, Object& pvarArrayAddIds, Object& pvarArrayLoginsRemove, Object& pvarArrayIdsRemove, Boolean bRemoveFromCurrentScopeOnly, Boolean bSendEmail) à Microsoft.SharePoint.SPUserCollection.UpdateMembers(Object objUpdateInfo, Object objAddIds, Object objRemoveLogins, Object objRemoveIds, Boolean fSendEmail) à Microsoft.SharePoint.SPUserCollection.AddCollection(SPUserInfo[] addUsersInfo, IEnumerable`1 addUsers) à Utils.ManageSPGroups.<>c__DisplayClass14.b__13()

Edit 2:

Just for information, this is my new function:

try 
{
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    {
        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl))
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (!IsUserMemberOfGroup(user.LoginName, groupName))
                {
                    SPGroup oGroup = web.SiteGroups[groupName];
                    oGroup.AddUser(user);
                 }
             });
          }
      }
 }
 catch (Exception ex)
 {
    SPEventLog.WriteError("AddUserIngroup: ", ex);
 }
1
  • Are you getting any error?
    – Aanchal
    May 15, 2014 at 12:45

2 Answers 2

3

You're elevating without creating a new site and web object, hence the AddGroup is not elevated at all!

You should create a new SPSite, open the correct SPWeb and then get the group from that elevated object.

You should proably ensure the user first as well, if you do not already

Ex.

using(SPSite site = new SPSite(SPContext.Current.Site.ID)
using (SPWeb oWebsite = site.OpenWeb())
{
    SPGroup oGroup = oWebsite.SiteGroups["Group_Name"];
    var spUser = oWebsite.EnsureUser(user);
    if(spUser != null)
         oGroup.AddUser(spUser);
}
1
  • I change my function with your advise. Now it work !!
    – Sancho
    May 16, 2014 at 13:02
0

Two more tips on that.

This creates the default groups in your web. The visitors group, member group and owner group. In case that they don't exist you can create them with that code:

                using (SPSite oSPsite = new SPSite(SiteUrl))
                {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        //Creates default SharPoint Groups 
                        oSPWeb.EnsureUser(userLoginName);
                        oSPWeb.CreateDefaultAssociatedGroups(userLoginName, userLoginName, oSPWeb.Title);
                        oSPWeb.Update();
                    }
                }

You can also use the webservice usergroup.asmx to add a user to a specific group: http://msdn.microsoft.com/en-us/library/ms772683(v=office.12).aspx

                usrgrpService.AddUserToGroup("Group_Name","User_Display_Name", "DOMAIN\\User_Alias","User_E-mail","Notes");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.