Partager via


Obtention des résultats de la recherche

Chaque résultat retourné par DirectorySearcher peut être récupéré comme un objet SearchResult. Chaque objet SearchResult contient un seul résultat et ses propriétés associées.

Les propriétés retournées dans chaque SearchResult sont contenues dans un objet ResultPropertyCollection. Les valeurs de ces propriétés sont contenues dans l'objet ResultPropertyValueCollection.

La méthode FindOne retourne un seul SearchResult. L'exemple suivant montre comment utiliser la méthode FindOne pour obtenir un seul SearchResult et récupérer les valeurs de toutes ses propriétés depuis ResultPropertyValueCollection.

' Bind to a specific user.
Dim path As String
path = "LDAP://CN=User Name,CN=users, DC=fabrikam,DC=com"
Dim entry As New DirectoryEntry(path)

' Create a DirectorySearcher object.
Dim mySearcher As New DirectorySearcher(entry)
mySearcher.SearchScope = SearchScope.Base

' Use the FindOne method to find the user object.
Dim resEnt As SearchResult = mySearcher.FindOne()

Dim propKey As String
For Each propKey In resEnt.Properties.PropertyNames
    ' Display each of the values for the property 
    ' identified by the property name.
    Dim prop As Object
    For Each prop In resEnt.Properties(propKey)
        Console.WriteLine("{0}:{1}", propKey, [prop].ToString())
    Next prop
Next propKey
// Bind to a specific user.
DirectoryEntry entry = new DirectoryEntry(
"LDAP://CN=User Name,CN=users,DC=fabrikam,DC=com");

// Create a DirectorySearcher object.
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.SearchScope = SearchScope.Base;

// Use the FindOne method to find the user object.
SearchResult resEnt = mySearcher.FindOne();

foreach(string propKey in resEnt.Properties.PropertyNames)
{
    // Display each of the values for the property 
    // identified by the property name.
    foreach (object property in resEnt.Properties[propKey])
    {
        Console.WriteLine("{0}:{1}", propKey, property.ToString());
    }
}

Lorsque la recherche trouve un ou plusieurs résultats, utilisez la méthode FindAll. Cette méthode retourne une collection d'objets SearchResult contenus dans l'objet SearchResultCollection. Utilisez une instruction foreach pour parcourir la collection SearchResultCollection et obtenir les données de chaque objet SearchResult.

L'exemple suivant utilise un filtre de recherche avec des caractères génériques et la méthode FindAll afin de rechercher tous les utilisateurs du conteneur Users dont le nom d'utilisateur commence par « test ». Toutes les valeurs de propriétés associées à chaque objet du jeu de résultats sont également récupérées de l'objet ResultPropertyValueCollection.

Dim results As SearchResultCollection = Nothing

Try
    ' Bind to the users container.
    Dim path As String = "LDAP://CN=users,DC=fabrikam,DC=com"
    path = "LDAP://CN=Users,DC=strohmadom,DC=nttest,DC=microsoft,DC=com"
    Dim entry As New DirectoryEntry(path)

    ' Create a DirectorySearcher object.
    Dim mySearcher As New DirectorySearcher(entry)

    ' Set a filter for users with the name test.
    mySearcher.Filter = "(&(objectClass=user)(anr=test*))"

    ' Use the FindAll method to return objects to a SearchResultCollection.
    results = mySearcher.FindAll()

    ' Iterate through each SearchResult in the SearchResultCollection.
    Dim searchResult As SearchResult
    For Each searchResult In results
        ' Display the path of the object found.
        Console.WriteLine("Search properties for {0}", _
            searchResult.Path)

        ' Iterate through each property name in each SearchResult.
        Dim propertyKey As String
        For Each propertyKey In searchResult.Properties.PropertyNames
            ' Retrieve the value assigned to that property name 
            ' in the ResultPropertyValueCollection.
            Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyKey)

            ' Iterate through values for each property name in each SearchResult.
            Dim propertyValue As Object
            For Each propertyValue In valueCollection
                ' Handle results. Be aware that the following 
                ' WriteLine() only returns readable results for 
                ' properties that are strings.
                Console.WriteLine("{0}:{1}", _
                    propertyKey, _
                    propertyValue.ToString())
            Next propertyValue
        Next propertyKey
    Next searchResult
Finally
    ' To prevent memory leaks, always call 
    ' SearchResultCollection.Dispose() manually.
    If Not results Is Nothing Then
        results.Dispose()
        results = Nothing
    End If
End Try
SearchResultCollection results = null;

try
{
    // Bind to the users container.
    string path = "LDAP://CN=users,DC=fabrikam,DC=com";
    DirectoryEntry entry = new DirectoryEntry(path);

    // Create a DirectorySearcher object.
    DirectorySearcher mySearcher = new DirectorySearcher(entry);

    // Set a filter for users with the name test.
    mySearcher.Filter = "(&(objectClass=user)(anr=test*))";

    // Use the FindAll method to return objects to a 
    // SearchResultCollection.
    results = mySearcher.FindAll();

    // Iterate through each SearchResult in the SearchResultCollection.
    foreach (SearchResult searchResult in results)
    {
        // Display the path of the object found.
        Console.WriteLine("Search properties for {0}", searchResult.Path);

        // Iterate through each property name in each SearchResult.
        foreach (string propertyKey in 
            searchResult.Properties.PropertyNames)
        {
            // Retrieve the value assigned to that property name 
            // in the ResultPropertyValueCollection.
            ResultPropertyValueCollection valueCollection = 
                searchResult.Properties[propertyKey];

            // Iterate through values for each property name in each 
            // SearchResult.
            foreach (Object propertyValue in valueCollection)
            {
                // Handle results. Be aware that the following 
                // WriteLine only returns readable results for 
                // properties that are strings.
                Console.WriteLine(
                    "{0}:{1}", 
                    propertyKey, 
                    propertyValue.ToString());
            }
        }
    }
}
finally
{
    // To prevent memory leaks, always call 
    // SearchResultCollection.Dispose() manually.
    if (null != results)
    {
        results.Dispose();
        results = null;
    }
}

Pour récupérer uniquement des valeurs de propriétés spécifiques pour les objets retournés dans le jeu de résultats dans le cas de l'exemple de code précédent, vous pouvez remplacer les deux instructions foreach internes par des instructions fournissant le nom des propriétés voulues, comme illustré par les instructions suivantes.

Console.WriteLine(resEnt1.Properties("cn")(0))
Console.WriteLine(resEnt1.Properties("objectClass")(1))
Console.WriteLine(resEnt1.Properties["cn"][0]);
Console.WriteLine(resEnt1.Properties["objectClass"][1]);

Dans ces instructions, la propriété spécifique est nommée et indexée. Si les propriétés contiennent plusieurs valeurs, vous devez énumérer les valeurs. Pour plus d'informations sur l'énumération des valeurs pour les propriétés, voir Lecture des propriétés ayant plusieurs valeurs.

Une autre solution fournie par l'objet ResultPropertyValueCollection est la propriété Item qui récupère une valeur à une position d'index spécifiée dans les propriétés contenant plusieurs valeurs. Le mot clé Item est utilisé dans Visual Basic .NET, mais dans C#, l'implémentation de Item est un tableau contenant la position d'index pour la valeur à récupérer. L'exemple suivant montre comment utiliser Item.

' Bind to a specific user.
Dim path As String = "LDAP://CN=User Name,CN=users,DC=fabrikam,DC=com"
Dim entry As New DirectoryEntry(path)

' Create a DirectorySearcher object.
Dim searcher As New DirectorySearcher(entry)

' Use the FindOne method to find the object, which in this case, is the user
' indicated by User Name and assign it to a SearchResult.
Dim searchResult As SearchResult = searcher.FindOne()

' Create a ResultPropertyValueCollection object to get the values for the 
' memberOf attribute for this user.
Dim propertyName As String = "memberOf"
Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyName)

Try
    ' Write the value contained in index position 5 in the memberOf attribute.
    Console.WriteLine(valueCollection(5).ToString())
Catch argumentEx As ArgumentOutOfRangeException
    ' The property contains no value in position 5.
    Console.WriteLine("The {0} property contains no value at the specified index.", propertyName)
End Try
// Bind to a specific user.
string path = "LDAP://CN=User Name,CN=users,DC=fabrikam,DC=com";
DirectoryEntry entry = new DirectoryEntry(path);

// Create a DirectorySearcher object.
DirectorySearcher searcher = new DirectorySearcher(entry);

// Use the FindOne method to find the object, which in this case, is the user
// indicated by User Name, and assign it to a SearchResult.
SearchResult searchResult = searcher.FindOne();

// Create a ResultPropertyValueCollection object to get the values for the 
// memberOf attribute for this user.
string propertyName = "memberOf";
ResultPropertyValueCollection valueCollection = searchResult.Properties[propertyName];

try
{
    // Write the value contained in index position 5 in the memberOf attribute.
    Console.WriteLine(valueCollection[5].ToString());
}
catch (ArgumentOutOfRangeException)
{
    // The property contains no value in position 5.
    Console.WriteLine(
        "The {0} property contains no value at the specified index.", 
        propertyName);
}

Pour les résultats de la recherche, System.DirectoryServices ne prend pas en charge les types de retours suivants :

  • ADS_PROV_SPECIFIC
  • ADSTYPE_CASEIGNORE_LIST
  • ADSTYPE_OCTET_LIST
  • ADSTYPE_PATH
  • ADSTYPE_POSTALADDRESS
  • ADSTYPE_TIMESTAMP
  • ADSTYPE_NETADDRESS
  • ADSTYPE_FAXNUMBER
  • ADSTYPE_EMAIL
  • ADSTYPE_BACKLINK
  • ADSTYPE_HOLD
  • ADSTYPE_TYPEDNAME
  • ADSTYPE_REPLICAPOINTER
  • ADSTYPE_UNKNOWN
  • ADSTYPE_PROV_SPECIFIC

Voir aussi

Référence

System.DirectoryServices
DirectorySearcher
SearchResult
SearchResultCollection
ResultPropertyCollection
ResultPropertyValueCollection

Concepts

Recherche dans l'annuaire
Lecture des propriétés ayant plusieurs valeurs

Send comments about this topic to Microsoft.

Copyright © 2007 par Microsoft Corporation. Tous droits réservés.