C#Active Directory - 读出电子邮件NullReferencesException

时间:2016-09-12 13:03:16

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

我试图获取所有用户在我们公司域中的电子邮件地址。 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());
    }
}

1 个答案:

答案 0 :(得分:0)

中可能有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();
}