列出所有使用目录服务的本地用户

问题描述:

我创建的以下方法似乎不起作用。在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

使用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

以下几种不同的方式来获取本地计算机名称:

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;