C#编程,如何通过给定的domain和group name 利用DirectorySearcher的Filter查询出这个group下的所有user?

解决方案 »

  1.   

    自己结贴,方法如下:public string[] getUsers(string domainName, string groupName)
    {
    string[] ret = null;

    DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainName,null,null,AuthenticationTypes.Secure);
    DirectorySearcher domainSearcher = new DirectorySearcher(domain);
    domainSearcher.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
    //domainSearcher.SearchScope = SearchScope.Base;
    DirectoryEntry group = domainSearcher.FindOne().GetDirectoryEntry(); if(group != null)
    {
    StringBuilder sb = new StringBuilder();
    //start an ldap filter
    sb.Append("(|");
    using (group)
    {
    foreach (string s in group.Properties["member"])
    {
    sb.AppendFormat("(distinguishedName={0})", s);
    }
    } //end the filter
    sb.Append(")"); //now use the filter to find all those users
    //and just ask for what you want
    DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + domainName,null,null,AuthenticationTypes.Secure);
        
    using (searchRoot)
    {
    DirectorySearcher ds = new DirectorySearcher(
    searchRoot,
    sb.ToString(), //our filter we built
    new string[]{ "sAMAccountName"}
    );

    using (SearchResultCollection users = ds.FindAll())
    {
    if(users != null)
    {
    ArrayList list = new ArrayList();
    string userName = null;
    foreach (SearchResult user in users)
    {
    userName = user.Properties["sAMAccountName"][0].ToString();
    list.Add(userName);
    }
    ret = new string[list.Count];
    list.CopyTo(0,ret,0,list.Count);
    }
    }

    }

    return ret; }