列出所有使用目录服务的本地用户 [英] list all local users using directory services
问题描述
我创建的以下方法似乎不起作用.在foreach循环上总是会发生错误.
The following method I created seem does not work. An error always happens on foreach loop.
NotSupportedException未处理...提供程序不支持搜索并且无法搜索WinNT://WIN7,计算机.
NotSupportedException was unhandled...The provider does not support searching and cannot search WinNT://WIN7,computer.
我正在查询本地计算机
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
}
}
}
推荐答案
您不能使用 WinNT
提供程序.从文档中:
You cannot use a DirectorySearcher
with the WinNT
provider. From the documentation:
使用
DirectorySearcher
对象使用轻型目录访问协议(LDAP)对Active Directory域服务层次结构进行搜索和执行查询.LDAP是唯一由系统提供的Active Directory服务接口(ADSI)提供程序,它支持目录搜索.
Use a
DirectorySearcher
object to search and perform queries against an Active Directory Domain Services hierarchy using Lightweight Directory Access Protocol (LDAP). LDAP is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports directory searching.
相反,请使用 DirectoryEntry.Children
属性以访问您的 <代码>计算机对象,然后使用 SchemaClassName
属性查找 User
对象.
Instead, use the DirectoryEntry.Children
property to access all child objects of your Computer
object, then use the SchemaClassName
property to find the children that are User
objects.
使用LINQ:
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry computerEntry = new DirectoryEntry(path))
{
IEnumerable<string> userNames = computerEntry.Children
.Cast<DirectoryEntry>()
.Where(childEntry => childEntry.SchemaClassName == "User")
.Select(userEntry => userEntry.Name);
foreach (string name in userNames)
Console.WriteLine(name);
}
没有LINQ:
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry computerEntry = new DirectoryEntry(path))
foreach (DirectoryEntry childEntry in computerEntry.Children)
if (childEntry.SchemaClassName == "User")
Console.WriteLine(childEntry.Name);
这篇关于列出所有使用目录服务的本地用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!