Language: EN

consultar-usuarios-y-ordenadores-de-active-directory-con-c

Get users and computers from Active Directory with C#

If you are system administrators with Active Directory, you will be used to dealing with the management of hundreds or even thousands of users and computers.

In these circumstances, it is often useful to make queries to Active Directory from C# to access, filter, or execute actions quickly and conveniently from one of our developments.

With this objective, we share the necessary code to make queries for users and computers from Active Directory using C#.

Query users from Active Directory

For the code to work, it is necessary to import the System.DirectoryServices assembly;

The code to import users is as follows. You can customize the properties returned by the query to your liking. Remember to change XXXXXX to the name of your AD, and YYY to the extension.

public List<User> GetADUsers()
{
  List<User> rst = new List<User>();

  string DomainPath = "LDAP://DC=XXXXXX,DC=YYY";
  DirectoryEntry adSearchRoot = new DirectoryEntry(DomainPath); 
  DirectorySearcher adSearcher = new DirectorySearcher(adSearchRoot);

  adSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
  adSearcher.PropertiesToLoad.Add("samaccountname");
  adSearcher.PropertiesToLoad.Add("title");
  adSearcher.PropertiesToLoad.Add("mail");
  adSearcher.PropertiesToLoad.Add("usergroup");
  adSearcher.PropertiesToLoad.Add("company");
  adSearcher.PropertiesToLoad.Add("department");
  adSearcher.PropertiesToLoad.Add("telephoneNumber");
  adSearcher.PropertiesToLoad.Add("mobile");
  adSearcher.PropertiesToLoad.Add("displayname");
  SearchResult result;
  SearchResultCollection iResult = adSearcher.FindAll();

  User item;
  if (iResult != null)
  {
    for (int counter = 0; counter < iResult.Count; counter++)
    {
      result = iResult[counter];
      if (result.Properties.Contains("samaccountname"))
      {
        item = new User();

        item.UserName = (String)result.Properties["samaccountname"][0];

        if (result.Properties.Contains("displayname"))
        {
          item.DisplayName = (String)result.Properties["displayname"][0];
        }

        if(result.Properties.Contains("mail"))
        {
          item.Email = (String)result.Properties["mail"][0];
        }

        if (result.Properties.Contains("company"))
        {
          item.Company = (String)result.Properties["company"][0];
        }

        if (result.Properties.Contains("title"))
        {
          item.JobTitle = (String)result.Properties["title"][0];
        }

        if (result.Properties.Contains("department"))
        {
          item.Deparment = (String)result.Properties["department"][0];
        }

        if (result.Properties.Contains("telephoneNumber"))
        {
          item.Phone = (String)result.Properties["telephoneNumber"][0];
        }

        if (result.Properties.Contains("mobile"))
        {
          item.Mobile = (String)result.Properties["mobile"][0];
        }
        rst.Add(item);
      }
    }
  }
  
  adSearcher.Dispose();
  adSearchRoot.Dispose();

  return rst;
}

public class User
{
  public string UserName { get; set; }

  public string DisplayName { get; set; }

  public string Company { get; set; }

  public string Deparment { get; set; }

  public string JobTitle{ get; set; }

  public string Email { get; set; }

  public string Phone { get; set; }

  public string Mobile { get; set; }
}

Query computers from Active Directory

For its part, the necessary code to list the computers in the AD is as follows. Similarly, you can customize the properties returned to your liking, and do not forget to change XXXXXX and YYY to the name and extension of your AD, respectively.

public static List<Computer> GetADComputers()
{
  List<Computer> rst = new List<Computer>();

  string DomainPath = "LDAP://DC=XXXXXX,DC=YYY";
  DirectoryEntry adSearchRoot = new DirectoryEntry(DomainPath);
  DirectorySearcher adSearcher = new DirectorySearcher(adSearchRoot);

  adSearcher.Filter = ("(objectClass=computer)");
  adSearcher.PropertiesToLoad.Add("description");
  adSearcher.SizeLimit = int.MaxValue;
  adSearcher.PageSize = int.MaxValue;

  SearchResult result;
  SearchResultCollection iResult = adSearcher.FindAll();

  Computer item;

  for (int counter = 0; counter < iResult.Count; counter++)
  {
    result = iResult[counter];

    string ComputerName = result.GetDirectoryEntry().Name;
    if (ComputerName.StartsWith("CN=")) ComputerName = ComputerName.Remove(0, "CN=".Length);
    item = new Computer();
    item.ComputerName = ComputerName;

    if (result.Properties.Contains("description"))
    {
      item.Description = (String)result.Properties["description"][0];

    }
    rst.Add(item);
  }

  adSearcher.Dispose();
  adSearchRoot.Dispose();

  return rst;
}

public class Computer
{
  public string ComputerName { get; set; }
  
  public string Description { get; set; }
}

We hope the code is useful to you and if you have any questions, do not hesitate to leave us your comment!