【问题标题】:How to use LINQ in C# to query windows local user accounts如何在 C# 中使用 LINQ 查询 windows 本地用户帐户
【发布时间】:2014-02-03 06:46:12
【问题描述】:

我想使用 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"]获取描述。那么是否可以使用'Description'之类的属性进行查询?

【问题讨论】:

    标签: c# sql linq adsi directoryentry


    【解决方案1】:

    我对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,然后再检查 .StartsWith 或 Contains 或任何其他字符串检查操作:

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

    【讨论】:

    • 在尝试上述情况时遇到以下异常:'对象引用未设置为对象的实例。'
    • 检查我的更新,在检查StartsWith之前先检查null。
    【解决方案2】:

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

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

    【讨论】:

    • 我正在尝试使用本地用户的名为“Description”的属性进行查询。但是我们不能直接从 childEntry.Description 等目录条目访问该属性。它通过以下方式获取:ChildEntry.属性[“描述”]。我想知道是否有办法使用此特定属性进行查询。
    【解决方案3】:

    这是我如何让它工作的。

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多