2011-11-19 60 views
5

我創建的以下方法似乎不起作用。在foreach循環中總是發生錯誤。列出所有使用目錄服務的本地用戶

NotSupportedException was unhandled ...提供程序不支持 搜索,無法搜索WinNT:// WIN7,計算機。

我查詢本地機器

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

你會得到什麼錯誤? – row1

+0

NotSupportedException未處理..............提供程序不支持搜索,無法搜索WinNT:// WIN7,計算機。 – ikel

+0

感謝清理我的問題 – ikel

回答

13

使用DirectoryEntry.Children property訪問您Computer object的所有子對象,並使用SchemaClassName property發現是User object一切都兒童。

使用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); 
}   

沒有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

太棒了,它的工作原理,非常感謝BACON – ikel

-1

以下幾種不同的方式來獲取本地計算機名稱:

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

下一個是一個獲取當前用戶名的方法:

string name = System.Windows.Forms.SystemInformation.UserName; 
相關問題