简体   繁体   中英

C# Active Directory - Read out Email NullReferencesException

I'm trying to get the e-mail adresses of all user's in our company domain. 99% work but sometimes there is y NullReferenceException in my Output.

Code:

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

There might be a NullReferenceException in the line

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

If in the Properties["mail"] returns a null value or its Value property is null , then the attempt to call ToString() will lead to an exception.

This will help in this case (C# 6 syntax)

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM