Enumerating Users with LDAP

Oct 09
2009

I’m sure there are lots of other tutorials, blog posts and actual documentation telling you how to do this, and this probably goes for a lot of the things I’ll post here, but this blog isn’t necessarily for other people. I’m beginning to realise that a lot of the code I post here is simply for my own benefit, and if it happens to coincide with the needs of someone else, that’s fine.

Anyway, I’m currently on-site again so I don’t have a lot of time to play and post snippets, but the LDAP code I was toying with this morning struck me as something I might want to revisit at some point in the future. It’s not exactly rocket science, but I often find that a short piece of working code can be an essential starting point when embarking on the understanding of a complex new library (for example, knowing that the technology is called LDAP and even understanding what that means, doesn’t tell you which .NET assemblies you should be investigating).

The following code is a C# console application which simply enumerates the users that the current account has access to know about in the given domain. An administrator running this should see everyone, but a lowly user with minimal rights may see only themselves (or possibly nothing at all!).

using System;
using System.Collections.Generic;
using System.DirectoryServices;
 
namespace ADTest
{
  class Program
  {
    static void Main(string[] args)
    {
      DirectoryEntry entry = new DirectoryEntry("LDAP://FM");
      DirectorySearcher search = new DirectorySearcher(entry); 
      search.Filter = "(&(objectClass=user)(objectCategory=person))";
      SearchResultCollection src = search.FindAll();
 
      Console.WriteLine(src.Count);
      foreach (SearchResult sr in src)
      {
        List<string> props = new List<string>();
        foreach (string propName in sr.Properties.PropertyNames)
        {
          props.Add(propName + "=[" + sr.Properties[propName] + "]");
        }
        Console.WriteLine(String.Join(", ", props.ToArray()) + "\n");
      }
    }
  }
}

This immediately gives me something to play with, it tells me I should investigate System.DirectoryServices, it tells me something about the way active directory search results are organised, and it tells me there is a curious filter syntax to investigate…

Visit Our Friends!

A few highly recommended friends...

Archives

All entries, chronologically...

Pages List

General info about this blog...