1

我知道 stackoverflow 中已经给出了很多方法,但就我而言,所有这些方法都需要很长时间。我发布了一个需要更少时间但实施起来仍然太长的方法。请帮助我,以减少执行时间。还要考虑到我使用的是 .net 2.0 框架。

        try
        {
            List<string> lstEmails = new List<string>();
            string filter1 = string.Format("(anr={0})", "groupname");
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = filter1;
            searcher.SearchScope = SearchScope.Subtree;
            searcher.PropertiesToLoad.Add("mail");
            IEnumerable res = (IEnumerable)searcher.FindOne().GetDirectoryEntry().Invoke("members");
            //IEnumerable<string> rest = (IEnumerable<string>)res;

            if (res != null)
            {
                try
                {
                    int index = 0;
                    foreach (IEnumerable resl in res)
                    {
                        DateTime start = DateTime.Now;
                        DirectoryEntry dr = new DirectoryEntry(resl);
                        string strEmail = null;
                        if (dr.Properties["mail"].Value != null)
                        {
                            strEmail = dr.Properties["mail"].Value.ToString();
                            Console.WriteLine(strEmail);
                            DateTime stop = DateTime.Now;
                            Console.WriteLine((stop - start).TotalMinutes.ToString());
                            index++;
                            Console.WriteLine(index.ToString());
                        }
                        if (!string.IsNullOrEmpty(strEmail))
                        {
                            // groupMemebers.Add("sam",strEmail);
                        }
                    }
                }
                catch { }
            }


        }
        catch { }

这是你建议的方法达罗..

    DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain, "domainname" + strLDAPUserName, strLDAPPassword);
        DomainController controller = DomainController.FindOne(context);
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}",controller.Domain), strLDAPUserName, strLDAPPassword, AuthenticationTypes.Secure);
List<string> userList = new List<string>();  
        DateTime StartTime = DateTime.Now;   
        using (DirectorySearcher ds = new DirectorySearcher(entry)) 
        {
            ds.PropertiesToLoad.Add("mail");  
            ds.PageSize = 10000;
            string DistingushiedName = "CN=" + groupName + ",OU=Users,dc=CompanyName,dc=com";
            ds.Filter = "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:="+DistingushiedName+"))";   
            ds.SearchScope = SearchScope.Subtree; 
            try 
            {
                foreach (SearchResult user in ds.FindAll())   
                {
                    try  
                    {
                        userList.Add(user.Path);//.Properties["mail"][0].ToString()); 
                    }
                    catch (Exception E)    
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
            catch(Exception E)    
            {
                throw new Exception(E.Message); 
            }
            DateTime EndTime = DateTime.Now;
            TimeSpan Dif = EndTime.Subtract(StartTime);
        } 
4

3 回答 3

0

这是您的解决方案:-

string[] email = new string[0];

DirectoryEntry entry = new DirectoryEntry("LDAP://OU=Users,dc=me,dc=com", username, password);
string groupName = "GroupName";//Group NAme

DirectorySearcher groupSearch = new DirectorySearcher(entry);
groupSearch.Filter = "(SAMAccountName=" + groupName + ")";
groupSearch.PropertiesToLoad.Add("member");
SearchResult groupResult = groupSearch.FindOne(); // getting the members who belongs to the concern groupname

if (groupResult != null)
 {
    email = new string[groupResult.Properties["member"].Count];  //creatign an array to store all the email address
    for (int iSearchLoop = 0; iSearchLoop < groupResult.Properties["member"].Count; iSearchLoop++)
      {
         string userName = groupResult.Properties["member"][iSearchLoop].ToString();
         int index = userName.IndexOf(',');
         userName = userName.Substring(0, index).Replace("CN=", "").ToString(); // the name of the user will be fetched.

         DirectorySearcher search = new DirectorySearcher(entry);
         search.Filter = "(name=" + userName + ")";
         search.PropertiesToLoad.Add("mail");
         SearchResult result = search.FindOne(); //finding the mail id
         if (result != null)
          {
            email[iSearchLoop] = result.Properties["mail"][0].ToString(); //assigning the mail id to an array....
          }
      }
}

希望这可以帮助你

于 2012-10-08T13:49:45.697 回答
0

嘿,这是正确的方法...

  try
        {
            List<string> ReturnArray = new List<string>();
            DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domainName, domainName + "\\" + UserName, Password);
            DomainController controller = DomainController.FindOne(context);
            string LDAPAddress = string.Format("LDAP://{0}", controller.Domain);
            DirectoryEntry deDirEntry = new DirectoryEntry(LDAPAddress, UserName, Password);
            deDirEntry.AuthenticationType = AuthenticationTypes.Secure;

            DirectorySearcher mySearcher = new DirectorySearcher(deDirEntry);
            mySearcher.PropertiesToLoad.Add("distinguishedName");
            string sFilter = String.Format("(&(objectcategory=group)(cn=" + GroupName + "))");

            mySearcher.Filter = sFilter;
            mySearcher.Sort.Direction = SortDirection.Ascending;
            mySearcher.Sort.PropertyName = "cn";
            SearchResult result;
            DirectoryEntry ResultEntry;
            result = mySearcher.FindOne();
            ResultEntry = result.GetDirectoryEntry();
            GroupName = ResultEntry.Properties["distinguishedName"].Value.ToString();
            mySearcher = new DirectorySearcher(deDirEntry);
            mySearcher.PropertiesToLoad.Add("cn");
            mySearcher.PropertiesToLoad.Add("mail");
            sFilter = String.Format("(&(objectClass=person)(memberOf={0}))", GroupName);
            mySearcher.Filter = sFilter;
            mySearcher.Sort.Direction = SortDirection.Ascending;
            mySearcher.Sort.PropertyName = "cn";
            SearchResultCollection results;
            results = mySearcher.FindAll();
            foreach (SearchResult resEnt in results)
            {
                ResultPropertyCollection propcoll = resEnt.Properties;
                foreach (string key in propcoll.PropertyNames)
                {
                    if (key == "mail")
                    {
                        foreach (object values in propcoll[key])
                        {
                            if (!String.IsNullOrEmpty(values.ToString()))
                            {
                                ReturnArray.Add(values.ToString());
                                Console.WriteLine(values.ToString());
                            }
                        }
                    }
                }
            }

            return ReturnArray;
        }
        catch
        {
            return null;
        }

谢谢大家的宝贵建议

于 2012-10-10T14:42:14.533 回答
0

很简单(如果您的 AD 是 2003 R2 或更高版本):

        List<string> userList = new List<string>();
        DateTime StartTime = DateTime.Now;
        using (DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry ("GC://DC=YourDomain,DC=com")))
        {
            ds.PropertiesToLoad.Add("mail");
            ds.PageSize = 10000;
            ds.Filter = "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:=YOUR_GROUP'S DN))";
            ds.SearchScope = SearchScope.Subtree;
            try
            {
                foreach (SearchResult user in ds.FindAll())
                {
                    try
                    {
                        userList.Add(user.Path);//.Properties["mail"][0].ToString());
                    }
                    catch (Exception E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
            catch(Exception E) 
            {
                throw new Exception(E.Message);
            }
            DateTime EndTime = DateTime.Now;
            TimeSpan Dif = EndTime.Subtract(StartTime);

        }

将 YOUR_GROUP'S DN 替换为您的组的专有名称...

memberof:1.2.840.113556.1.4.1941:=是“新”LDAP_MATCHING_RULE_IN_CHAIN 运算符,并检索所有组成员。在此处查看您的 AD 是否已准备好并获取更多信息。

编辑:

我给了你一个答案,但解释可能会有所帮助。

一般来说,您应该避免 ANR 搜索,因为它们会扩展为大型通配符 OR 查询。仅当您不知道哪个属性包含您要搜索的名称时才使用它们。它们比显式 AND 搜索要慢得多

其次,如果您拥有多个域,则应关闭推荐追踪,除非您想搜索所有域直到获得成功。在这种情况下,最好执行 GC:// 而不是 LDAP:// 搜索来查找您要查找的对象,而不是对该对象执行 LDAP 搜索。根据您要查找的内容,GC 查询可能就足够了

编辑2:

修改代码以提供更多错误信息并获取用户路径而不是 E-Mail。

于 2012-10-08T17:40:11.680 回答