Compartir a través de


Getting Search Results

Each result returned by DirectorySearcher can be retrieved as a SearchResult object. Each SearchResult object contains a single result and its associated properties.

The properties returned in each SearchResult are contained in a ResultPropertyCollection object. The values for these properties are contained in the ResultPropertyValueCollection object.

The FindOne method will return a single SearchResult. The following example shows how to use the FindOne method to obtain a single SearchResult and retrieve the values for all of its properties from the 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());
    }
}

When the search retrieves one or more results, use the FindAll method. This method returns a collection of SearchResult objects that are contained in the SearchResultCollection object. Use a foreach statement to iterate through the SearchResultCollection and obtain data from individual SearchResult objects.

The following example uses a wild card search filter and the FindAll method to find all users in the Users container that have "test" at the beginning of the user name. All the property values associated with each object in the result set are also retrieved from the ResultPropertyValueCollection object.

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

To retrieve only specific property values for the objects returned in the result set for the previous code example, you can replace the inner two foreach statements with statements that provide the names of the properties that you want, as shown in the following statements.

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 these statements, the specific property is named and indexed. If the properties contain multiple values, you need to enumerate the values. For more information about enumerating values for properties, see Reading Properties with Multiple Values.

Another option provided by the ResultPropertyValueCollection object is the Item property, which retrieves a value at a specified index position in properties that contains multiple values. The Item keyword is used in Visual Basic .NET, but in C#, the implementation of Item is an array that contains the index position for the value to retrieve. The following example shows how to use 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);
}

For search results, System.DirectoryServices does not support the following return types:

  • 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

See Also

Reference

System.DirectoryServices
DirectorySearcher
SearchResult
SearchResultCollection
ResultPropertyCollection
ResultPropertyValueCollection

Concepts

Searching the Directory
Reading Properties with Multiple Values

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.