从AD中根据group name获取group下所有的用户信息

下面的方法是可以用来在获取AD group下所有的member的用户信息的一个例子。

public UserInfoDataSet GetUsersFromADGroup(string path, string userName, string password, string groupName)
{
   UserInfoDataSet dsUsers = new UserInfoDataSet();

   try
   {
       using (DirectoryEntry de = new DirectoryEntry(path, userName, password))
       {
           DirectorySearcher deSearch = new DirectorySearcher(de);
           deSearch.Filter = "(&(objectClass=group)(sAMAccountName=" + groupName + "))";
           deSearch.PropertiesToLoad.Add("member");
           SearchResult r = deSearch.FindOne();

           if (r.Properties["member"] == null)
           {
              throw new Exception("member propertity is null for the AD group.");
           }
           foreach (string dn in r.Properties["member"])
           {
               DirectoryEntry user = new DirectoryEntry(path + "/" + dn, userName, password, AuthenticationTypes.Secure);
               if (user.SchemaClassName == "user")
               {
                   string name = GetProperty(user, "sAMAccountName");
                   string fullName = GetProperty(user, "displayName");

                   if (!string.IsNullOrEmpty(name))
                   {
                       UserInfoDataSet.T_COM_USER_INFORRow row = dsUsers.T_COM_USER_INFOR.NewT_COM_USER_INFORRow();
                       row.USER_ID = -1;
                       row.USER_NAME = name;
                       row.NAME = fullName;
                       row.USER_TYPE = LRMEConstant.UserType.SLA;
                       dsUsers.T_COM_USER_INFOR.Rows.Add(row);
                    }
               }
            }
        }
   }
   catch (Exception ex)
   {
      throw ex;
   }

   return dsUsers;
}

public string GetProperty(DirectoryEntry entry, string PropertyName)
{
    if (entry != null && entry.Properties.Contains(PropertyName))
    {
        return entry.Properties[PropertyName].Value.ToString();
     }
     else
     {
        return string.Empty;
     }
}

原创文章,转载请注明: 转载自闲云博客

本文链接地址: 从AD中根据group name获取group下所有的用户信息

发表评论

电子邮件地址不会被公开。 必填项已用*标注