如何将用户帐户添加到组(成员)

时间:2019-01-16 11:24:05

标签: c# .net-3.5

我想将Windows帐户用户添加到组中 我使用这种方法:

public bool AddUserToGroup(PrincipalContext ctx, string userId, string groupName)
{
     try
    {
          GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
          group.Members.Add(ctx, IdentityType.UserPrincipalName, userId);
          group.Save();
          return true;
    }
    catch
    {
         return false;
    }
}

当我通过以下方法使用此方法

PrincipalContext 
new PrincipalContext(ContextType.Domain, "Lab.net");

它工作正常。

但是当我使用

PrincipalContext with username and password it have exception
new PrincipalContext(ContextType.Domain, "Lab.net","administrator","P@ssw0rd");

例外是:

  

System.DirectoryServices.AccountManagement.PrincipalOperationException:无法检索有关域的信息(1355)。      在System.DirectoryServices.AccountManagement.Utils.GetDcName处(字符串computerName,字符串domainName,字符串siteName,Int32标志)      在System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo()      在System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsForestName()      在System.DirectoryServices.AccountManagement.ADUtils.ArePrincipalsInSameForest中(主体p1,主体p2)      在System.DirectoryServices.AccountManagement.ADStoreCtx.UpdateGroupMembership(主体组,DirectoryEntry de,NetCred凭据,AuthenticationTypes authTypes)      在System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(主体p,StoreCtx storeCtx,GroupMembershipUpdater updateGroupMembership,NetCred凭证,AuthenticationTypes authTypes)      在System.DirectoryServices.AccountManagement.ADStoreCtx.Update(主体p)      在System.DirectoryServices.AccountManagement.Principal.Save()

我可以使用PrincipalContext创建用户,但不能将用户加入组。

1 个答案:

答案 0 :(得分:0)

我这样做:

public bool AddUserToGroup(PrincipalContext ctx, DirectoryEntry userId, string groupName)
{
    try
    {
        //GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
        //group.Members.Add(ctx, IdentityType.UserPrincipalName, userId);
        //group.Save();
        GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName);
        if (groupPrincipal != null) {
            DirectoryEntry entry = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();
            entry.Invoke("Add", new object[] { userId.Path.ToString() });
            userId.CommitChanges();
        }
        else {
            return true;
        }

        return true;
    }
    catch
    {
        return false;
    }
}