【问题标题】:C# Active Directory - Read out Email NullReferencesExceptionC# Active Directory - 读出电子邮件 NullReferencesException
【发布时间】:2017-01-19 22:19:40
【问题描述】:

我正在尝试获取我们公司域中所有用户的电子邮件地址。 99% 的工作,但有时我的输出中有 y NullReferenceException。

代码:

string dom = "mydomain";

System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dom); //domain, user, password
System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(entry);

ds.Filter = ("(objectClass=User)");
int count = 1;

foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll())
{
    try
    {
        System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry(); 
        String email = de.Properties["mail"].Value.ToString();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

【问题讨论】:

  • 我实际上没有在您的帖子中看到任何问题。你有什么问题?
  • 如果有人知道为什么codeString email = de.Properties["mail"].Value.ToString();code
  • //编辑:我收到 377 个电子邮件地址,但在我们的域中有 383...不能为这 6 个用户工作?
  • 您是否尝试过使用AD Explorer 之类的工具实际查看这些用户并检查他们的属性以确保他们确实拥有与其他人一样的邮件属性?
  • 抱歉,有些用户没有电子邮件地址

标签: c# .net windows exception active-directory


【解决方案1】:

该行中可能有一个NullReferenceException

String email = de.Properties["mail"].Value.ToString();

如果在Properties["mail"] 中返回一个null 值或其Value 属性为null,那么尝试调用ToString() 将导致异常。

这在这种情况下会有所帮助(C# 6 语法)

String email = de.Properties["mail"]?.Value?.ToString();

String email = null;
if (de.Properties["mail"] != null && de.Properties["mail"].Value != null)
{
    email = de.Properties["mail"].Value.ToString();
}

【讨论】:

  • @Flow - 欢迎您。如果帖子解决了您的问题,请将帖子标记为“回答”。
猜你喜欢
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
相关资源
最近更新 更多