如何在C#中使用LINQ来查询Windows本地用户帐户

时间:2014-02-03 06:46:13

标签: c# sql linq adsi directoryentry

我想使用ADSI从C#查询Windows本地用户帐户。 由于使用了WinNt提供程序,因此不支持Directory SEarcher。 我正在做以下事情:

DirectoryEntries entries = hostMachineDirectory.Children;
var users = from DirectoryEntry childEntry in hostMachineDirectory.Children
                where (childEntry.Name.StartsWith("User1"))
                select childEntry;

可以使用名称查询。无法获得childEntry.Description之类的描述。可以使用属性childEntry.Properties["Description"]来获取描述。那么可以使用“描述”等属性进行查询吗?

3 个答案:

答案 0 :(得分:0)

如果你想获得字符串,你应该这样做:

DirectoryEntries entries = hostMachineDirectory.Children;
var users = (from DirectoryEntry childEntry in hostMachineDirectory.Children
                where (childEntry.Name.StartsWith("User1"))
                select childEntry).SingleOrDefault<string>();

答案 1 :(得分:0)

我对AD知之甚少,但我想,假设Properties["Description"].Value返回字符串,你可以这样试试:

var users = from DirectoryEntry childEntry in entries
            where ((string)childEntry.Properties["Description"].Value).StartsWith("User1")
            select childEntry;

好了,因为你确认我的假设是错误的,Properties["Description"].Value并不总是返回字符串,有时会返回NULL,我们需要先检查null,然后再检查.StartsWithContains或任何其他字符串检查操作:

var users = from DirectoryEntry childEntry in entries
            where childEntry.Properties["Description"].Value != null &&
                ((string)childEntry.Properties["Description"].Value).StartsWith("User1")
            select childEntry;

答案 2 :(得分:0)

这是我如何让它发挥作用。

var users = from DirectoryEntry childEntry in hostMachineDirectory.Children
            where childEntry.SchemaClassName == "User"
            select childEntry;
try { 
    var UserName = users.Single(s => s.Properties["Description"].Value.ToString().StartsWith("Whatever description")).Name;
    Console.WriteLine("User: " + UserName);
}
catch (Exception e) { 
    var err = e.Message;
    Console.WriteLine("Error message: " + err);
}