Enumerating Active Directory object properties using C#

I had to look up for a properties in Active Directory against my login. Since I didn’t even know the name of properties, I had to enumerate through them. Here is the code.

1. Create C# application and add a configuration file “app.config”.

2. Update it as follows:

<configuration>
  <appSettings>
    <add key="ADDomain" value="mydomain"/>
    <add key="username" value="username"/>
  </appSettings>
</configuration>

Update your “domain” and “username”.

3. Add following code in Main method (usually in program.cs file)

try
{
    using (DirectoryEntry de = new DirectoryEntry(@"LDAP://" + ConfigurationSettings.AppSettings["ADDomain"]))
    {
        using (DirectorySearcher adSearch = new DirectorySearcher(de))
        {
            adSearch.Filter = "(sAMAccountName=" + ConfigurationSettings.AppSettings["username"] + ")";
            SearchResult sr = adSearch.FindOne();
            foreach (string prop in sr.Properties.PropertyNames)
            {
                Console.WriteLine(prop + " = " +sr.Properties[prop][0].ToString());
            }
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

NOTE: If your computer is on domain on which you are searching, you can get “current” domain by doing the following:

DirectoryEntry deDomain = new DirectoryEntry();
deDomain.Name.Replace("DC=", "")

So you won’t need to have the ADDomain config entry.

PERFORMANCE NOTE: When you know the property name you need, specify it as follows before calling “find” method:

adSearch.PropertiesToLoad.Add("mail");

This will only load the given property instead of loading the whole object.

Comments

Popular posts from this blog

Unable to delete Shared Services Provider in SharePoint (MOSS)

The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

Cannot add a SimpleContent column to a table containing element columns or nested relations