【问题标题】:How to add a user account to a group (member of)如何将用户帐户添加到组(成员)
【发布时间】:2019-01-16 11:24:05
【问题描述】:

我想将 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(字符串计算机名,字符串域名,字符串站点名,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 创建用户,但无法将用户加入群组。

【问题讨论】:

    标签: c# .net-3.5


    【解决方案1】:

    我这样做:

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

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 2021-04-22
      相关资源
      最近更新 更多