[英]list all local users using directory services
The following method I created seem does not work.我创建的以下方法似乎不起作用。 An error always happens on foreach loop.在 foreach 循环中总是会发生错误。
NotSupportedException was unhandled...The provider does not support searching and cannot search WinNT://WIN7,computer. NotSupportedException 未处理...提供程序不支持搜索,无法搜索 WinNT://WIN7,computer。
I'm querying the local machine我在查询本地机器
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
}
}
}
You cannot use a DirectorySearcher
with the WinNT
provider .您不能将DirectorySearcher
与WinNT
提供程序一起使用。 From the documentation:从文档:
Use a
DirectorySearcher
object to search and perform queries against an Active Directory Domain Services hierarchy using Lightweight Directory Access Protocol (LDAP).使用DirectorySearcher
对象通过轻型目录访问协议 (LDAP) 搜索和执行针对 Active Directory 域服务层次结构的查询。 LDAP is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports directory searching. LDAP 是唯一支持目录搜索的系统提供的 Active Directory 服务接口 (ADSI) 提供程序。
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 .相反,使用DirectoryEntry.Children
属性访问Computer
对象的所有子对象,然后使用SchemaClassName
属性查找属于User
对象的子对象。
With LINQ:使用 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);
}
Without LINQ:没有 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);
The following are a few different ways to get your local computer name:以下是获取本地计算机名称的几种不同方法:
string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);
The next one is a way to get the current user name:下一个是获取当前用户名的方法:
string name = System.Windows.Forms.SystemInformation.UserName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.