using appsettings:ldapdomain get list of ldap attributes for employeeid in csharp

Here is a sample code that retrieves the list of LDAP attributes for EmployeeID using the appsettings for LDAP domain:

main.cs
using System.DirectoryServices;
using Microsoft.Extensions.Configuration;

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load appsettings.json
            IConfigurationRoot config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", true, true)
                .Build();

            string ldapDomain = config["appsettings:ldapdomain"];
            string employeeId = "12345"; // Replace with the actual EmployeeID

            // Set up the LDAP connection
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapDomain);

            // Search for the employee with the specified EmployeeID
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = "(&(objectCategory=person)(objectClass=user)(employeeID=" + employeeId + "))";

            SearchResult result = searcher.FindOne();

            if (result != null)
            {
                // Get the list of LDAP attributes for the employee
                PropertyCollection properties = result.Properties;

                foreach (string propertyName in properties.PropertyNames)
                {
                    Console.WriteLine("{0} : {1}", propertyName, string.Join(",", properties[propertyName].Cast<string>()));
                }
            }
            else
            {
                Console.WriteLine("Employee not found.");
            }

            // Release resources
            searcher.Dispose();
            entry.Dispose();
        }
    }
}
1587 chars
48 lines

You will need to have a valid LDAP domain specified in your appsettings.json file. Replace the employeeId variable with the actual employee ID that you want to retrieve the attributes for. The code uses the DirectorySearcher class to search for the employee with the specified EmployeeID and retrieves the list of LDAP attributes for that employee.

gistlibby LogSnag