2011-11-19 17 views
5

El siguiente método que he creado parece no funcionar. Siempre ocurre un error en el bucle foreach.enumera todos los usuarios locales que utilizan servicios de directorio

NotSupportedException fue controlada ... El proveedor no admite búsqueda y no puede buscar WinNT: // Win7, ordenador.

estoy consultando la máquina local

private static void listUser(string computer) 
{ 
     using (DirectoryEntry d= new DirectoryEntry("WinNT://" + 
        Environment.MachineName + ",computer")) 
     { 
      DirectorySearcher ds = new DirectorySearcher(d); 
      ds.Filter = ("objectClass=user"); 
      foreach (SearchResult s in ds.FindAll()) 
      { 

       //display name of each user 

      } 
     } 
    } 
+1

¿Qué error obtienes? – row1

+0

NotSupportedException no se ha manejado .............. El proveedor no admite búsquedas y no puede buscar WinNT: // WIN7, computadora. – ikel

+0

gracias por limpiar mi pregunta – ikel

Respuesta

13

Uso del DirectoryEntry.Children property acceder a todos los objetos secundarios de la Computer object, y utilizar el SchemaClassName property para encontrar todos los niños que son User object s.

Con LINQ:

var path = string.Format("WinNT://{0},computer", Environment.MachineName); 

using (var computerEntry = new DirectoryEntry(path)) 
{ 
    var userNames = from DirectoryEntry childEntry in computerEntry.Children 
        where childEntry.SchemaClassName == "User" 
        select childEntry.Name; 

    foreach (var name in userNames) 
     Console.WriteLine(name); 
}   

Sin LINQ:

var path = string.Format("WinNT://{0},computer", Environment.MachineName); 

using (var computerEntry = new DirectoryEntry(path)) 
    foreach (DirectoryEntry childEntry in computerEntry.Children) 
     if (childEntry.SchemaClassName == "User") 
      Console.WriteLine(childEntry.Name); 
+0

genial, funciona, gracias mucho BACON – ikel

-1

Las siguientes son algunas maneras diferentes de obtener el nombre del equipo local:

string name = Environment.MachineName; 
string name = System.Net.Dns.GetHostName(); 
string name = System.Windows.Forms.SystemInformation.ComputerName; 
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”); 

La siguiente es una forma de obtener el nombre de usuario actual:

string name = System.Windows.Forms.SystemInformation.UserName; 
Cuestiones relacionadas