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

ike*_*kel 8 c# active-directory

我创建的以下方法似乎不起作用.在foreach循环中总会发生错误.

NotSupportedException未处理...提供程序不支持搜索,无法搜索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

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

BAC*_*CON 17

使用DirectoryEntry.Children属性访问Computer对象的所有子对象,并使用SchemaClassName属性查找作为User对象的所有子对象.

使用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);
}           
Run Code Online (Sandbox Code Playgroud)

没有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);
Run Code Online (Sandbox Code Playgroud)