我创建的以下方法似乎不起作用。在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
}
}
}
答案 0 :(得分:14)
使用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);
答案 1 :(得分:-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;