0

我正在尝试在 Active Directory 中搜索特定用户,我正在使用 FindAll 方法。当我调用它时它给了我一个错误。我该如何解决这个问题?

这是我得到的例外:

System.DirectoryServices.dll 中出现“ System.Runtime.InteropServices.COMException ”类型的未处理异常

    SearchResultCollection sResults = null;
    try
    {
        //modify this line to include your domain name
        string path = "LDAP://microsistemas.com";
        //init a directory entry
        DirectoryEntry dEntry = new DirectoryEntry(path);

        //init a directory searcher
        DirectorySearcher dSearcher = new DirectorySearcher(dEntry);

        //This line applies a filter to the search specifying a username to search for
        //modify this line to specify a user name. if you want to search for all
        //users who start with k - set SearchString to "k";
        dSearcher.Filter = "(&(objectClass=user))";

        //perform search on active directory
        sResults = dSearcher.FindAll();

        //loop through results of search
        foreach (SearchResult searchResult in sResults)
        {
            if (searchResult.Properties["CN&"][0].ToString() == "Administrator")
            {
                ////loop through the ad properties
                //foreach (string propertyKey in
                //searchResult.Properties["st"])
                //{

                //pull the collection of objects with this key name
                ResultPropertyValueCollection valueCollection =
                searchResult.Properties["manager"];

                foreach (Object propertyValue in valueCollection)
                {

                    //loop through the values that have a specific name
                    //an example of a property that would have multiple
                    //collections for the same name would be memberof
                    //Console.WriteLine("Property Name: " + valueCollection..ToString());
                    Console.WriteLine("Property Value: " + (string)propertyValue.ToString());

                    //["sAMAccountName"][0].ToString();
                }
                //}
                Console.WriteLine(" ");
            }
        }
    }
    catch (InvalidOperationException iOe)
    {
        //
    }
    catch (NotSupportedException nSe)
    {
        //
    }
    finally
    {

        // dispose of objects used
        if (sResults != null)
            sResults.Dispose();

    }
    Console.ReadLine();
}
4

1 回答 1

0

如果您使用的是 .NET 3.5 及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM) 命名空间。

基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:

// set up domain context - limit to the OU you're interested in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "DC=microsistemas,DC=com"))
{
    // find a user
    Principal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }
}

新的 S.DS.AM 使得在 AD 中与用户和组一起玩变得非常容易!

在此处阅读更多信息:

于 2016-12-08T18:21:15.117 回答