DirectorySearcher.FindAll()有时可以工作,有时不工作

时间:2012-05-17 06:15:47

标签: c# active-directory directoryservices

我正在尝试从Active Directory获取用户列表。基本搜索过滤器是:

objectCategory=person  
objectClass=user  
name=*'username'* 

这是代码:

public static List<User> GetByUserName(string userName)
{
    DirectorySearcher ds = new DirectorySearcher();
    List<User> userList = new List<User>();
    try
    {
        ds.SearchRoot = new DirectoryEntry("LDAP://domain","user_name", "password");
        ds.Filter = "(|(&(objectCategory=person)(objectClass=user)(name=*" + userName + "*)))";
        ds.PropertyNamesOnly = true;
        ds.PropertiesToLoad.Add("samaccountname");
        ds.PropertiesToLoad.Add("name");
        ds.PropertiesToLoad.Add("mail");
        ds.Sort = new SortOption("name", SortDirection.Ascending);    
        foreach (SearchResult sr in ds.FindAll())
        {
            DirectoryEntry de = sr.GetDirectoryEntry();
            User newUser = new User();
            newUser.Name = de.Name.Substring(3);
            newUser.AccountName = (string)de.Properties["samaccountname"].Value ?? " <Undefined>";
            newUser.EmailAddress = (string)de.Properties["mail"].Value ?? "<Undefined>";
            userList.Add(newUser);
        }
    }
    catch (Exception ex)
    {
        throw new Exception("There was a problem search the Active Directory: " + ex.Message);
    }   
    return userList;
}

问题是,有时我会得到结果,但有时候不是同一个userName。这很奇怪 当它正常工作时,我会在10-15秒内得到结果 但有时它会搜索120秒,然后我收到了超时。或者更早,如果我设置ServerTimeLimit 我不知道为什么它有时工作正常,为什么有时不工作。这似乎是随机的 是代码中的问题还是其他地方的问题?
谢谢你的帮助。

0 个答案:

没有答案