Ошибка поиска определенного пользователя в Active Directory с помощью метода C # FindAll

Я пытаюсь найти конкретного пользователя в Active Directory, использую метод FindAll. Когда я его вызываю, возникает ошибка. Как я могу решить эту проблему?

Это исключение, которое я получаю:

Необработанное исключение типа System.Runtime.InteropServices.COMException произошло в System.DirectoryServices.dll

    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();
}

person Bernal Bogantes Conejo    schedule 08.12.2016    source источник
comment
вы знакомы с _1 _ ..? также почему вы не оборачиваете текст фильтра вокруг " ", а не используете dSearcher.Filter = "(&(objectClass=user))";?   -  person MethodMan    schedule 08.12.2016


Ответы (1)


Если вы используете .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!

Об этом подробнее здесь:

person marc_s    schedule 08.12.2016