StevenL StevenL - 1 year ago 159
C# Question

C# Testing for null

I'm using C# to write a simple program to read Active Directory and display the value held in a AD field on a Windows form program.

If a property doesn't exist then the program crashes, below is my code, how can I catch this and move on to the next field without doing a try/catch for each and every attribute?

DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;

//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();

Answer Source

Just checking usr.Properties["telephoneNumber"] will not work. You must check the actual value. The reason the error is occuring is because you're calling ToString() on Value which is null.

user.Properties will always return a PropertyValueCollection, regardless of the property name entered into the collections indexer.


var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value;                  // Will return null and not error

You need to check the value itself, the best way through the null coalescing operator:

textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value 
                            ?? "Not found").ToString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download