leora
leora

Reputation: 196459

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"];

Upvotes: 1

Views: 540

Answers (3)

Andrew T Finnell
Andrew T Finnell

Reputation: 13628

Updated to work

The example you have will return a single Property. The problem is that the return is a Collection. I recommend doing

// Or String if you know it's always a string
var mailCollection = resEnt.Properties["mail"].Cast<Object>(); 
var emailAddress = mailCollection.FirstOrDefault();

If you use FirstOrDefault it will return the first value or null. If you use Single or [0] you will have to perform a validation step before hand or catch the Exception that is thrown when no results are returned.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564403

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;

Upvotes: 5

Jace Rhea
Jace Rhea

Reputation: 5018

Use the cast operation in conjuntion with LINQ to get the first object.

var email = resEnt.Properties["mail"].Cast<object>.FirstOrDefault();

Upvotes: 0

Related Questions