【问题标题】:Why am I getting "Object reference not set to an instance of an object" from GetDirectoryEntry()?为什么我从 GetDirectoryEntry() 中得到“对象引用未设置为对象的实例”?
【发布时间】:2023-06-05 10:39:01
【问题描述】:

我有一些奇怪的错误。

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://11.111.111.11", "user", "1");

DirectorySearcher searcher = new DirectorySearcher(directoryEntry)
{
    PageSize = int.MaxValue,
    Filter = "(&(objectClass=user)(sAMAccountName=" + txt + "*))"
};

SearchResultCollection resultCollection = searcher.FindAll();
foreach (SearchResult result in resultCollection)
{
    if (result != null)
    {
        users.Add(new ObjectTest(
        result.GetDirectoryEntry().Properties["samaccountname"].Value as string,
        result.GetDirectoryEntry().Properties["givenName"].Value as string,
        result.GetDirectoryEntry().Properties["sn"].Value as string,
        result.GetDirectoryEntry().Properties["mail"].Value as string));
    }
}

directoryEntry.Close();

当我搜索一些用户时,我会收集它们,然后在 foreach 中使用它们。 例如:我输入 user 并获取 5 个用户的集合,然后填充我的数组。

但有时我会收集到这里给我错误的用户:

例如,我输入 test 并且我知道我有用户“test”并且我看到我的集合具有正确的计数,但是在 result.GetDirectoryEntry() 之后我得到异常对象引用未设置为对象的实例。

我在网站上找不到类似的东西。

注意: 集合具有正常的对象计数,并且 SearchResult 不为 null 它具有正常的路径! 谢谢!

【问题讨论】:

  • 注意:Collection 有正常的对象数,SearchResult 不为 null 它有正常的 Path!
  • 你能检查一下“result.GetDirectoryEntry()”是否也不为空吗?关于“Properties[]”的同样问题。
  • 那么我是否正确理解是 .Value 引发了异常?
  • 我猜 也许 GetDirectoryEntry 本身正在从自己的代码中抛出 NullReferenceException,但这似乎不太可能。

标签: c# .net active-directory directoryservices


【解决方案1】:

这是我的评论,已回答:

检查Properties getter 的结果;大概其中一个返回 null,这就是您的 NullReferenceException 的来源(当您尝试获取 null 属性的 Value 时)。

编辑: 无法删除答案,但根据 cmets 中的@baldpate,PropertyCollection.Item[string] 永远不会返回 null,因此以上不是对 NullReferenceException 的解释。无论如何,寻找异常来源的策略是:

  1. 将每个方法调用放在自己的行中,并将结果存储在一个变量中。
  2. 一次一行地遍历您的代码,测试输出,直到找到为空的那个。

【讨论】:

  • DirectoryEntry.Properties 和 PropertyCollection.Item[string] 永远不会返回 null。
  • @baldpate,从 OP 的 cmets 看来,PropertyCollection.Item[string] 确实可以返回 null。我个人不知道。
  • 来自反射器PropertyCollection.Item[string] 将始终返回一个PropertyValueCollection 实例,即使给定的属性名称类似于“@#$%^”。
  • 再次感谢您!我会听从你的建议