2011-03-14 45 views
2

我正尝试从自定义登录页面将用户添加到现有组。现在,我从SPWeb.CurrentUser获取当前用户没有任何问题。我可以查看所有这些当前用户组,但现在我遇到了将该用户添加到现有组的问题。我想我需要使用SPRoleDefinition和SPRoleAssignment,但我可以找到的是如何使用这些类更改组的权限。有谁知道我可以通过groupname将该用户添加到组中吗?SharePoint 2010:从代码中将用户添加到组

谢谢!

回答

3

您可以使用此功能将用户添加到当前站点。您需要传递组名称和用户名。

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. 
    } 
} 
相关问题