mshaji
asked on
Add a user to Owner Group programmatically
Dears,
I have 60 sub sites under a site collection and each sub site have "Owner Group" permission (SharePoint permission group). Now here I needed to add a user to this group programmatically. Here adding it manually to these sub sites are much time taking. So can anyone give an idea to add a user to these sub sites together by C# coding.
Regards
Shaji
I have 60 sub sites under a site collection and each sub site have "Owner Group" permission (SharePoint permission group). Now here I needed to add a user to this group programmatically. Here adding it manually to these sub sites are much time taking. So can anyone give an idea to add a user to these sub sites together by C# coding.
Regards
Shaji
test
Follow the below code.
private void AddUserToAGroup(string userLoginName, string userGroupName)
{
//Executes this method with Full Control rights even if the user does not otherwise have Full Control
SPSecurity.RunWithElevated Privileges (delegate
{
//Don't use context to create the spSite object since it won't create the object with elevated privileges but with the privileges of the user who execute the this code, which may casues an exception
using (SPSite spSite = new SPSite(Page.Request.Url.To String()))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
try
{
//Allow updating of some sharepoint lists, (here spUsers, spGroups etc...)
spWeb.AllowUnsafeUpdates = true;
SPUser spUser = spWeb.EnsureUser(userLogin Name);
if (spUser != null)
{
SPGroup spGroup = spWeb.Groups[userGroupName ];
if (spGroup != null)
spGroup.AddUser(spUser);
}
}
catch (Exception ex)
{
//Error handling logic should go here
}
finally
{
spWeb.AllowUnsafeUpdates = false;
}
}
}
});
}
private void AddUserToAGroup(string userLoginName, string userGroupName)
{
//Executes this method with Full Control rights even if the user does not otherwise have Full Control
SPSecurity.RunWithElevated
{
//Don't use context to create the spSite object since it won't create the object with elevated privileges but with the privileges of the user who execute the this code, which may casues an exception
using (SPSite spSite = new SPSite(Page.Request.Url.To
{
using (SPWeb spWeb = spSite.OpenWeb())
{
try
{
//Allow updating of some sharepoint lists, (here spUsers, spGroups etc...)
spWeb.AllowUnsafeUpdates = true;
SPUser spUser = spWeb.EnsureUser(userLogin
if (spUser != null)
{
SPGroup spGroup = spWeb.Groups[userGroupName
if (spGroup != null)
spGroup.AddUser(spUser);
}
}
catch (Exception ex)
{
//Error handling logic should go here
}
finally
{
spWeb.AllowUnsafeUpdates = false;
}
}
}
});
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
solved