Code to add SPUser in SPGroup
Following code snippet demonstrate the way to programmatically add SPUser in SPGroup...
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSiteTemp = new SPSite(SPContext.Current.Web.Url))
using (SPWeb spWebTemp = spSiteTemp.OpenWeb())
{
spWebTemp.AllowUnsafeUpdates = true;
SPGroup spGroup = spWebTemp.SiteGroups["MySPGroup"];
SPUser spUser = spWebTemp.EnsureUser("DomainName\" + msUser.UserName);
//Adding group name in temporary arraylist to check SPUser's existing group.
ArrayList arrayListGroups = new ArrayList();
foreach (SPGroup tempGroup in spUser.Groups)
{
arrayListGroups.Add(tempGroup.Name.ToLower());
}
if ((spUser.Groups.Count < 1)
|| ((spUser.Groups.Count > 1)
&& (!arrayListGroups.Contains("myspgroup"))))
{
spGroup.AddUser(spUser);
}
spWebTemp.AllowUnsafeUpdates = false;
}
});
}
catch (SPException)
{
throw;
}