James Wilson
James Wilson

Reputation: 5150

How to find manager of department

I'm working with Active Directory currently. I am able to pull a list of everyone who works in a department, but I am not sure how to tell which one is the manager.

public void MemberOf(string department)
        {
            DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");

            DirectorySearcher ds = new DirectorySearcher(de);

            ds.Filter = ("(&(objectCategory=person)(objectClass=User)(department=" + department + "))");
            ds.SearchScope = SearchScope.Subtree;

            foreach (SearchResult temp in ds.FindAll())
            {
                string test1 = temp.Path;
            }
        }

This will return a list of people one of them being the manager the rest being direct reports to the manager.

Upvotes: 0

Views: 1490

Answers (1)

Sam
Sam

Reputation: 113

This isn't the best implementation, but without knowing what you want to use it for...how you're going to be getting the data...etc etc this is a quick and dirty implementation:

private void Test(string department)
    {
        //Create a dictionary using the manager as the key, employees for the values
        List<Employee> employees = new List<Employee>();

        DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");
        DirectorySearcher ds = new DirectorySearcher(de);

        ds.Filter = String.Format(("(&(objectCategory=person)(objectClass=User)(department={0}))"), department);
        ds.SearchScope = SearchScope.Subtree;

        foreach (SearchResult temp in ds.FindAll())
        {
            Employee e = new Employee();

            e.Manager = temp.Properties["Manager"][0].ToString();
            e.UserId = temp.Properties["sAMAccountName"][0].ToString();
            e.Name = temp.Properties["displayName"][0].ToString();

            employees.Add(e);
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public string Manager { get; set; }
        public string UserId { get; set; }
    }

Upvotes: 2

Related Questions