Michael Kniskern
Michael Kniskern

Reputation: 25260

How do I loop through a PropertyCollection

Can anyone provide an example of how to loop through a System.DirectoryServices.PropertyCollection and output the property name and value?

I am using C#.

The PropertyCollection does not have a Name/Value property. It does have a PropertyNames and Values, type System.Collection.ICollection. I do not know the baseline object type that makes up the PropertyCollection object.

Upvotes: 25

Views: 38869

Answers (10)

shahkalpesh
shahkalpesh

Reputation: 33476

See the value of PropertyValueCollection at runtime in the watch window to identify types of element, it contains & you can expand on it to further see what property each of the element has.

Adding to JaredPar's code:

PropertyCollection collection = GetTheCollection();
foreach ( PropertyValueCollection value in collection ) {
  // Do something with the value
  Console.WriteLine(value.PropertyName);
  Console.WriteLine(value.Value);
  Console.WriteLine(value.Count);
}

PropertyCollection is made up of PropertyValueCollection

Upvotes: 32

user2680296
user2680296

Reputation: 1

You really don't have to do anything magical if you want just a few items...

Using System;
Using System.DirectoryServices;
Using System.AccountManagement;

public void GetUserDetail(string username, string password)
{
    UserDetail userDetail = new UserDetail();
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "mydomain.com", username, password);

        //Authenticate against Active Directory
        if (!principalContext.ValidateCredentials(username, password))
        {
            //Username or Password were incorrect or user doesn't exist
            return userDetail;
        }

        //Get the details of the user passed in
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, principalContext.UserName);

        //get the properties of the user passed in
        DirectoryEntry directoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry;

        userDetail.FirstName = directoryEntry.Properties["givenname"].Value.ToString();
        userDetail.LastName = directoryEntry.Properties["sn"].Value.ToString();
    }
    catch (Exception ex)
    {
       //Catch your Excption
    }

    return userDetail;
}

Upvotes: 0

JaredPar
JaredPar

Reputation: 754645

Edit: I misread the OP as having said PropertyValueCollection not PropertyCollection. Leaving post up because other posts are referenceing it.

Are you just wanting to loop through each value in the collection? If so, this code will work:

PropertyValueCollection collection = GetTheCollection();
foreach ( object value in collection ) {
  // Do something with the value
}

Print out the Name / Value

Console.WriteLine(collection.Name);
Console.WriteLine(collection.Value);

Upvotes: 1

Bbb
Bbb

Reputation: 649

I'm not sure why this was so hard to find an answer to, but with the below code I can loop through all of the properties and pull the one I want and reuse the code for any property. You can handle the directory entry portion differently if you want

getAnyProperty("[servername]", @"CN=[cn name]", "description");

   public List<string> getAnyProperty(string originatingServer, string distinguishedName, string propertyToSearchFor)
    {
        string path = "LDAP://" + originatingServer + @"/" + distinguishedName;
        DirectoryEntry objRootDSE = new DirectoryEntry(path, [Username], [Password]);
// DirectoryEntry objRootDSE = new DirectoryEntry();

        List<string> returnValue = new List<string>();
        System.DirectoryServices.PropertyCollection properties = objRootDSE.Properties;
        foreach (string propertyName in properties.PropertyNames)
        {
            PropertyValueCollection propertyValues = properties[propertyName];
            if (propertyName == propertyToSearchFor)
            {
                foreach (string propertyValue in propertyValues)
                {
                    returnValue.Add(propertyValue);
                }
            }
        }

        return returnValue;
    }

Upvotes: 0

Mohammed Othman
Mohammed Othman

Reputation: 1

public string GetValue(string propertyName, SearchResult result)
{
    foreach (var property in result.Properties)
    {
        if (((DictionaryEntry)property).Key.ToString() == propertyName)
        {
            return ((ResultPropertyValueCollection)((DictionaryEntry)property).Value)[0].ToString();
        }
    }
    return null;
}

Upvotes: 0

long2know
long2know

Reputation: 1360

I posted my answer on another thread, and then found this thread asking a similar question.

I tried the suggested methods, but I always get an invalid cast exception when casting to DictionaryEntry. And with a DictionaryEntry, things like FirstOrDefault are funky. So, I simply do this:

var directoryEntry = adUser.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.RefreshCache();
var propNames = directoryEntry.Properties.PropertyNames.Cast<string>();
var props = propNames
    .Select(x => new { Key = x, Value = directoryEntry.Properties[x].Value.ToString() })
    .ToList();

With that in place, I can then easily query for any property directly by Key. Using the coalesce and safe navigation operators allows for defaulting to an empty string or whatever..

var myProp = props.FirstOrDefault(x => x.Key == "someKey"))?.Value ?? string.Empty;

And if I wanted to look over all props, it's a similar foreach.

foreach (var prop in props)
{
     Console.WriteLine($"{prop.Key} - {prop.Value}");
}

Note that the "adUser" object is the UserPrincipal object.

Upvotes: 1

user76071
user76071

Reputation:

I think there's an easier way

foreach (DictionaryEntry e in child.Properties) 
{
    Console.Write(e.Key);
    Console.Write(e.Value);
}

Upvotes: -1

Vladimir
Vladimir

Reputation: 51

usr = result.GetDirectoryEntry();
foreach (string strProperty in usr.Properties.PropertyNames)
{
   Console.WriteLine("{0}:{1}" ,strProperty, usr.Properties[strProperty].Value);
}

Upvotes: 5

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26956

The PropertyCollection has a PropertyName collection - which is a collection of strings (see PropertyCollection.Contains and PropertyCollection.Item both of which take a string).

You can usually call GetEnumerator to allow you to enumerate over the collection, using the usual enumeration methods - in this case you'd get an IDictionary containing the string key, and then an object for each item/values.

Upvotes: 6

antonioh
antonioh

Reputation: 2944

foreach(var k in collection.Keys) 
{
     string name = k;
     string value = collection[k];
}

Upvotes: 2

Related Questions