使用DirectorySearcher从大型AD组中获取SamAccountName

时间:2015-07-10 05:12:36

标签: c# asp.net c#-4.0 active-directory active-directory-group

我使用以下方法来查询来自大型AD组的成员。

try
{
    DirectoryEntry entry = new DirectoryEntry("LDAP://CN=My Distribution List,OU=Distribution Lists,DC=Fabrikam,DC=com");
    DirectorySearcher searcher = new DirectorySearcher(entry);
    searcher.Filter = "(objectClass=*)";

    uint rangeStep = 1000;
    uint rangeLow = 0;
    uint rangeHigh = rangeLow + (rangeStep - 1);
    bool lastQuery = false;
    bool quitLoop = false;

    do
    {
        string attributeWithRange;
        if(!lastQuery)
        {
            attributeWithRange = String.Format("member;range={0}-{1}", rangeLow, rangeHigh);
        }
        else
        {
            attributeWithRange = String.Format("member;range={0}-*", rangeLow);
        }           
        searcher.PropertiesToLoad.Clear();
        searcher.PropertiesToLoad.Add(attributeWithRange);
        SearchResult results = searcher.FindOne();
        foreach(string res in results.Properties.PropertyNames)
        {
            System.Diagnostics.Debug.WriteLine(res.ToString());
        }
        if(results.Properties.Contains(attributeWithRange))
        {
            foreach(object obj in results.Properties[attributeWithRange])
            {
                Console.WriteLine(obj.GetType());
                if(obj.GetType().Equals(typeof(System.String)))
                {
                }
                else if (obj.GetType().Equals(typeof(System.Int32)))
                {
                }
                Console.WriteLine(obj.ToString());
            }
            if(lastQuery)
            {
                quitLoop = true;
            }
        }
        else
        {
            lastQuery = true;
        }
        if(!lastQuery)
        {
            rangeLow = rangeHigh + 1;
            rangeHigh = rangeLow + (rangeStep - 1);
        }
    }
    while(!quitLoop);
}
catch(Exception ex)
{
    // Handle exception ex.
}

这里我想检索成员的SamAccountName以及他们的distinguishedName.Also我有一些包含跨域成员的组。能帮忙吗?

1 个答案:

答案 0 :(得分:2)

获取您通常需要调用DirectoryEntry.Properties [ PropertyName ]的任何属性的值。值,例如

var x = results.Properties["distinguishedName"].Value

对于某些索引值,可能需要提供索引属性[ PropertyName ] [X] .Value

如果结果中未默认填充值,则可能需要使用DirectorySearcher.PropertiesToLoad.Add( PropertyName )强制加载它;