25

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#.

@JaredPar - 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 basline object type that makes up the PropertyCollection object.

@JaredPar again - I originally mislabeled the question with the wrong type. That was my bad.

Update: Based on Zhaph - Ben Duguid input, I was able to develop the following code.

using System.Collections;
using System.DirectoryServices;

public void DisplayValue(DirectoryEntry de)
{
    if(de.Children != null)
    {
        foreach(DirectoryEntry child in de.Children)
        {
            PropertyCollection pc = child.Properties;
            IDictionaryEnumerator ide = pc.GetEnumerator();
            ide.Reset();
            while(ide.MoveNext())
            {
                PropertyValueCollection pvc = ide.Entry.Value as PropertyValueCollection;

                Console.WriteLine(string.Format("Name: {0}", ide.Entry.Key.ToString()));
                Console.WriteLine(string.Format("Value: {0}", pvc.Value));                
            }
        }      
    }  
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Michael Kniskern
  • 24,792
  • 68
  • 164
  • 231

10 Answers10

31

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);
}

EDIT: PropertyCollection is made up of PropertyValueCollection

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
  • This is the right way, it seems that PropertyValueCollection was the key to the right enumeration. All the other solutions suggest another indirect indexing (or either don't work). – Csaba Toth Feb 26 '13 at 18:38
  • Perfect, except in my case I needed to use `.ToString` on `.Value` because it couldn't be implicitly cast. – Chad Jan 08 '16 at 20:54
6

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.

Zhaph - Ben Duguid
  • 26,785
  • 5
  • 80
  • 117
5
usr = result.GetDirectoryEntry();
foreach (string strProperty in usr.Properties.PropertyNames)
{
   Console.WriteLine("{0}:{1}" ,strProperty, usr.Properties[strProperty].Value);
}
Michael Kniskern
  • 24,792
  • 68
  • 164
  • 231
Vladimir
  • 51
  • 1
  • 1
2
foreach(var k in collection.Keys) 
{
     string name = k;
     string value = collection[k];
}
antonioh
  • 2,924
  • 6
  • 26
  • 28
1

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.

long2know
  • 1,280
  • 10
  • 9
0

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

Using Statements: System, System.DirectoryServices, and 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;
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
0
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;
}
CDspace
  • 2,639
  • 18
  • 30
  • 36
0

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;
    }
Bbb
  • 517
  • 6
  • 27
0

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

I'm not sure I understand what you're asking 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);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
-1

I think there's an easier way

foreach (DictionaryEntry e in child.Properties) 
{
    Console.Write(e.Key);
    Console.Write(e.Value);
}
  • I got a System.InvalidCastException: Specified cast is not valid. when using this. – Despertar May 09 '12 at 19:55
  • This is the right methodology but uses the wrong type. A PropertyCollection contains PropertyValueCollection objects as per shahkalpesh's answer, not DictionaryEntry objects. – Bloopy Mar 04 '20 at 03:38