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

Get users and computers from Active Directory with C#

  • 3 min

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 query Active Directory from C# to access, filter, or execute actions quickly and conveniently from within our developments.

With this goal in mind, we share the necessary code to query 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 your AD name, 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; }
}
Copied!

Query Computers from Active Directory

On the other hand, the code needed to list the computers in the AD is as follows. You can also customize the returned properties to your liking, and don’t forget to change XXXXXX and YYY to your AD name and extension, 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; }
}
Copied!