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