testing for missing attributes on an AD search

I'm doing an active directory search (code below).  Some of the attributes I'm searching for don't exist on some of the people.  I'm trying to test for the values which may not be there before I access them and generate an error.  I found some code below to test for the existence of the values but it doesn't work.  I know I can always use Try & Catch but I'd rather have a method that can actually test than catch errors.

       DirectorySearcher search = new DirectorySearcher(entry);
       search.Filter = "(&(objectClass=user) (mail=" + account + "))";
// I'm adding in the fields that I want returned in my search
      search.PropertiesToLoad.Add("displayName");
      search.PropertiesToLoad.Add("SAMAccountName");
      search.PropertiesToLoad.Add("telephoneNumber");
      search.PropertiesToLoad.Add("mail");
      search.PropertiesToLoad.Add("mobile");
      search.PropertiesToLoad.Add("badPwdCount");
      search.PropertiesToLoad.Add("lockoutTime");

      SearchResult result = search.FindOne();

      if (result != null)
      {
// I was expecting the next two lines to tell me if the mail element exists
          Type t = result.GetType();
// p=null even though the mail element does exist
          PropertyInfo p = t.GetProperty("mail");
//mail contains the correct value even though p was null in the line above
          string mail=result.Properties["mail"][0].ToString();
dr761Asked:
Who is Participating?
 
Carl TawnConnect With a Mentor Systems and Integration DeveloperCommented:
p is null because "mail" isn't actually a property of the object, its purely a piece of metadata exposed through what is basically a HashTable.

So you can test for the existence of a element using the Contains() method:
if (result != null)
{
     string mail;

     if (result.Properties.Contains("mail"))
         mail = result.Properties["mail"][0];
}

Open in new window

0
 
dr761Author Commented:
Works great!  Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.