Recupero dei risultati della ricerca

Ogni risultato restituito da DirectorySearcher può essere recuperato come un oggetto SearchResult. Ogni oggetto SearchResult contiene un singolo risultato e le proprietà ad esso associate.

Le proprietà restituite in ogni oggetto SearchResult sono contenute in un oggetto ResultPropertyCollection. I valori per queste proprietà sono contenuti nell'oggetto ResultPropertyValueCollection.

Il metodo FindOne restituisce un singolo oggetto SearchResult. Nell'esempio riportato di seguito viene illustrato come utilizzare il metodo FindOne per ottenere un singolo oggetto SearchResult e recuperare i valori per tutte le proprietà relative da 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());
    }
}

Quando la ricerca recupera uno o più risultati, utilizzare il metodo FindAll. Questo metodo restituisce un insieme di oggetti SearchResult che sono contenuti nell'oggetto SearchResultCollection. Utilizzare un'istruzione foreach per scorrere SearchResultCollection e ottenere i dati da singoli oggetti SearchResult.

Nell'esempio riportato di seguito viene utilizzato un filtro di ricerca con caratteri jolly e il metodo FindAll per trovare tutti gli utenti nel contenitore il cui nome riporta all'inizio "test". Vengono recuperati anche tutti i valori delle proprietà associati a ogni oggetto nell'insieme dei risultati dall'oggetto 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;
    }
}

Per recuperare solo specifici valori delle proprietà per gli oggetti restituiti nell'insieme dei risultati per l'esempio di codice precedente, è possibile sostituire le due istruzioni foreach più interne che forniscono i nomi delle proprietà desiderate, come mostrato nelle istruzioni seguenti.

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

In queste istruzioni, la proprietà specifica è denominata e indicizzata. Se le proprietà contengono più valori, è necessario enumerare i valori. Per ulteriori informazioni sull'enumerazione dei valori, vedere Lettura di proprietà con più valori.

Un'altra opzione fornita dall'oggetto ResultPropertyValueCollection è la proprietà Item che recupera un valore nella posizione di indice specificata nelle proprietà che contengono più valori. La parola chiave Item viene utilizzata in Visual Basic .NET, ma in C# l'implementazione di Item è una matrice che contiene la posizione di indice del valore da recuperare. Nell'esempio riportato di seguito viene illustrato come utilizzare 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);
}

Per i risultati della ricerca, System.DirectoryServices non supporta i tipi restituiti seguenti:

  • 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

Vedere anche

Riferimenti

System.DirectoryServices
DirectorySearcher
SearchResult
SearchResultCollection
ResultPropertyCollection
ResultPropertyValueCollection

Concetti

Ricerca nella directory
Lettura di proprietà con più valori

Send comments about this topic to Microsoft.

Copyright © 2007 Microsoft Corporation. Tutti i diritti riservati.