Search code examples
c#directoryservices

In C# is there anyway to read a property directly (versus having to loop through PropertyNames)


I have the following code:

// Create a DirectorySearcher object.
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.SearchScope = SearchScope.Base;

// Use the FindOne method to find the user object.
SearchResult resEnt = mySearcher.FindOne();

foreach(string propKey in resEnt.Properties.PropertyNames)
{
   foreach (var property in resEnt.Properties[propKey])
   {
       Console.WriteLine("{0}:{1}", propKey, property.ToString());
   }
}

This works fine but I only need to get a single property called "mail". Is there anyway i can just read a single property without having to loop. I am looking for something like this:

var emailAddress =  resEnt.Properties["mail"];

Solution

  • You probably want:

    string emailAddress = (string)resEnt.Properties["mail"][0];
    

    Note that you might want to do some checking here to make sure there is a valid "mail" property:

    var mailProps = resEnt.Properties["mail"];
    string emailAddress = mailProps.Count > 0 ? (string)mailProps[0] : string.Empty;