2011-11-19 13 views
5

Il seguente metodo che ho creato sembra non funziona. Un errore si verifica sempre sul ciclo foreach.elenca tutti gli utenti locali che utilizzano i servizi di directory

NotSupportedException è stata gestita ... Il provider non supporta ricerca e non può cercare WinNT: // Win7, computer.

sto interrogando la macchina locale

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

Che errore ottieni? – row1

+0

NotSupportedException non gestito. .............. Il provider non supporta la ricerca e non può cercare WinNT: // WIN7, computer. – ikel

+0

grazie per aver pulito la mia domanda – ikel

risposta

13

Utilizzare il DirectoryEntry.Children property per accedere a tutti gli oggetti figlio del vostro Computer object, e utilizzare il SchemaClassName property per trovare tutti i bambini che sono 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); 
}   

Senza 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

grande, funziona, grazie molto BACON – ikel

-1

Di seguito sono diversi modi per ottenere il vostro nome del computer locale:

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

il prossimo è un modo per ottenere il nome utente corrente:

string name = System.Windows.Forms.SystemInformation.UserName; 
Problemi correlati