Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Cada resultado devuelto por DirectorySearcher se puede recuperar como un objeto SearchResult. Cada objeto SearchResult contiene un solo resultado y sus propiedades asociadas.
Las propiedades devueltas en cada SearchResult se incluyen en un objeto ResultPropertyCollection. Los valores de estas propiedades se incluyen en el objeto ResultPropertyValueCollection.
El método FindOne devolverá un solo SearchResult. El ejemplo siguiente muestra cómo utilizar el método FindOne para obtener un solo SearchResult y recuperar los valores de todas sus propiedades desde la 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());
}
}
Cuando la búsqueda recupere uno o más resultados, utilice el método FindAll. Este método devuelve una colección de objetos SearchResult que figuran en el objeto SearchResultCollection. Utilice una instrucción foreach para ejecutar una iteración en la SearchResultCollection y obtener datos de objetos SearchResult individuales.
El siguiente ejemplo utiliza un filtro de búsqueda comodín y el método FindAll para buscar todos los usuarios del contendor Users que tienen la palabra "test" al principio del nombre de usuario. Del objeto ResultPropertyValueCollection también se recuperan todas las propiedades de los valores asociados con cada objeto del conjunto de resultados.
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;
}
}
Para recuperar sólo valores de propiedades específicas de los objetos devueltos en el conjunto de resultados del ejemplo de código anterior, puede reemplazar las dos instrucciones foreach internas con instrucciones que proporcionen los nombres de las propiedades que desea, tal y como se muestra en las siguientes instrucciones.
Console.WriteLine(resEnt1.Properties("cn")(0))
Console.WriteLine(resEnt1.Properties("objectClass")(1))
Console.WriteLine(resEnt1.Properties["cn"][0]);
Console.WriteLine(resEnt1.Properties["objectClass"][1]);
En estas instrucciones, la propiedad específica tiene nombre y está indizada. Si las propiedades contienen varios valores, debe enumerarlos. Para obtener más información sobre cómo enumerar valores de propiedades, vea Leer propiedades con varios valores.
Otra opción proporcionada por el objeto ResultPropertyValueCollection es la propiedad Item, que recupera un valor en una posición de índice especificada que contiene varios valores. La palabra clave Item se utiliza en Visual Basic .NET, pero en C# la implementación de Item es una matriz que contiene la posición de índice del valor que se va a recuperar. En el ejemplo siguiente se muestra cómo utilizar 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);
}
En el caso de los resultados de la búsqueda, System.DirectoryServices no admite los siguientes tipos de valor devuelto:
- 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
Consulte también
Referencia
System.DirectoryServices
DirectorySearcher
SearchResult
SearchResultCollection
ResultPropertyCollection
ResultPropertyValueCollection
Conceptos
Buscar en el directorio
Leer propiedades con varios valores
Send comments about this topic to Microsoft.
Copyright © 2007 Microsoft Corporation. Reservados todos los derechos.