Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#

Active Directory Users and Computers

Rate me:
Please Sign up or sign in to vote.
4.94/5 (15 votes)
26 Jan 2013CPOL3 min read 87.5K   12.1K   60   19
Display Active Directory users and computers and export them to CSV or Excel document

Introduction

This article explains how to find users and computers in your domain and display all the information about them which have been saved in active directory and export the results to CSV or Excel file.

Background

If you have Windows Server, you can view all users in your domain by adding active directory role or its features. But if you don't use Windows Server and you are a member of a domain, just download ActiveDirectoryInformation.exe from the top of this page and run the application on your computer. All users and computers and their information will be displayed by using System.DirectoryServices.AccountManagement namespace and you can save results in Excel format. You can use this application even if you are not a domain admin.

Using the Code

We use System.DirectoryServices.AccountManagement namespace for working with active directory. To use this namespace, you should add System.DirectoryServices.AccountManagement to your project references.

To find users in active directory, first we should find domain name. This code returns domain name:

C#
string stringDomainName = 
  System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

Then we specify which information we want to save about each user and computer. As you can see in the code below, we define User class properties of user. Now we initialize User constructor which has eight arguments and save input data in User’s properties. We also define properties function which returns all saved properties of User.

C#
public class User
{
    public String SamAccountName { get; set; }
    public String DisplayName { get; set; }
    public String Name { get; set; }
    public String GivenName { get; set; }
    public String Surname { get; set; }
    public String Description { get; set; }
    public Boolean? Enabled { get; set; }
    public DateTime? LastLogon { get; set; }

    public User(String SamAccountName, String DisplayName, String Name, 
        String GivenName, String Surname, String Description,
        Boolean? Enabled, DateTime? LastLogon)
    {
        this.SamAccountName = SamAccountName;
        this.DisplayName = DisplayName;
        this.Name = Name;
        this.GivenName = GivenName;
        this.Surname = Surname;
        this.Description = Description;
        this.Enabled = Enabled;
        this.LastLogon = LastLogon;
    }
    public List<string> Properties()
    {
        return new List<string> { SamAccountName, DisplayName, Name, 
          GivenName, Surname, Description, Enabled.ToString(), LastLogon.ToString() };
    }
    public int UserPropertiesTotal = 8;
    public static string[] StringArrayUesrProperties = { "SamAccountName", 
      "DisplayName", "Name", "GivenName", "Surname", 
      "Description", "Enabled", "LastLogon" };
}

We also make a list of users which saves information about all users:

C#
public Users Users1 = new Users();
public class Users : List<User> { }

We do the same for computers too. First, we make a computer class and a list of all computers.

C#
public Computers Computers1 = new Computers();
public class Computers : List<Computer> { }
public class Computer
{
    public String SamAccountName { get; set; }
    public String DisplayName { get; set; }
    public String Name { get; set; }
    public String Description { get; set; }
    public Boolean? Enabled { get; set; }
    public DateTime? LastLogon { get; set; }

    public Computer(String SamAccountName, 
        String DisplayName, String Name, String Description,
        Boolean? Enabled, DateTime? LastLogon)
    {
        this.SamAccountName = SamAccountName;
        this.DisplayName = DisplayName;
        this.Name = Name;
        this.Description = Description;
        this.Enabled = Enabled;
        this.LastLogon = LastLogon;
    }
    public List<string> Properties()
    {
        return new List<string> { SamAccountName, DisplayName, 
          Name, Description, Enabled.ToString(), LastLogon.ToString() };
    }
    public int UserPropertiesTotal = 6;
    public static string[] StringArrayComputerProperties = { "SamAccountName", 
      "DisplayName", "Name", "Description", "Enabled", "LastLogon" };
}

After running the application, if user just clicks on Show button, then all users will be displayed. In this state after finding domain name, we use these classes:

  1. Initialize an instance of PrincipalContext which refers to that domain
  2. UserPrincipal for all user
  3. PrincipalSearcher to find each user in userPrincipal. In this example, we want to return all users so we use search.FindAll().

Now, we can search through all users and save those we want. If you don’t select any group or password in application interface, then all users will be displayed in DataGrid.

C#
private void ShowUsers()
{
    //Check password
    Boolean boolPass;
    //Check groups
    Boolean boolGroup;
    Users1.Clear();
    int intCounter = 0;
    PrincipalContext PrincipalContext1 = 
        new PrincipalContext(ContextType.Domain, stringDomainName);
    UserPrincipal UserPrincipal1 = new UserPrincipal(PrincipalContext1);
    PrincipalSearcher search = new PrincipalSearcher(UserPrincipal1);

    foreach (UserPrincipal result in search.FindAll())
    {
        //Check default pass
        if (checkBoxPass.IsChecked == true)
        {
            if (PrincipalContext1.ValidateCredentials
               (result.SamAccountName, PasswordBoxPass.Password))
            {
                boolPass = true;
            }
            else
            {
                boolPass = false;
            }
        }
        else
        {
            boolPass = true;
        }
        //Check group
        if (comboBoxGroups.SelectedIndex >= 0)
        {
            PrincipalSearchResult<Principal> PrincipalSearchResults1 = result.GetGroups();
            foreach (Principal PrincipalSearchResult1 in PrincipalSearchResults1)
            {
                if (PrincipalSearchResult1.Name == comboBoxGroups.SelectedValue.ToString())
                {
                    boolGroup = true;
                    break;
                }
            }
        }
        else
        {
            boolGroup = true;
        }
        //Add user
        if (boolPass && boolGroup)
        {
            User User1 = new User(result.SamAccountName, result.DisplayName, 
                result.Name, result.GivenName, result.Surname,
                result.Description, result.Enabled, result.LastLogon);
            Users1.Add(User1);
            intCounter++;
        }
    }
    search.Dispose();
    datagridResult.ItemsSource = Users1;
    datagridResult.Items.Refresh();
    MessageBox.Show(intCounter + " users. ");
    EnumDataGrid1 = EunmDataGrid.users;
}

Sometimes, you want to display users from specific groups, for example, domain admins. In this situation, you can select that group. Also, if you enter a password, then only users who have the same password will be displayed.

Image 1

To find all computers, we use the same method, but instead of UserPrincipal, we use ComputerPrincipal and also we don’t need to check passwords or groups.

C#
private void ShowComputers()
{
    Computers1.Clear();
    int intCounter = 0;
    PrincipalContext PrincipalContext1 = 
         new PrincipalContext(ContextType.Domain, stringDomainName);
    ComputerPrincipal ComputerPrincipal1 = new ComputerPrincipal(PrincipalContext1);
    PrincipalSearcher search = new PrincipalSearcher(ComputerPrincipal1);
    foreach (ComputerPrincipal result in search.FindAll())
    {
        Computer Computer1 = new Computer(result.SamAccountName, result.DisplayName, 
          result.Name, result.Description, result.Enabled, result.LastLogon);
        Computers1.Add(Computer1);
        intCounter++;
    }
    search.Dispose();
    datagridResult.ItemsSource = Computers1;
    datagridResult.Items.Refresh();
    MessageBox.Show(intCounter + " computers. ");
    EnumDataGrid1 = EunmDataGrid.computers;
}

Now by pressing show button, all information about all users or computers in active directory of your domain will be shown in DataGrid.

C#
private void buttonShow_Click(object sender, RoutedEventArgs e)
{
    try
    {
        if (stringDomainName != null)
        {
            datagridResult.ItemsSource = null;
            if (radiobuttonUsers.IsChecked == true)
            {
                ShowUsers();

            }
            else if (radiobuttonComputers.IsChecked == true)
            {
                ShowComputers();
            }
        }
        else
        {
            MessageBox.Show("Your computer is not a member of domain", 
              "Active Directory Users", MessageBoxButton.OK, MessageBoxImage.Information);
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }
}

Export Result to CSV

We define two functions to export results to CSV. First one for exporting users and second one for exporting computers. Both functions are the same and their only difference is the type of data which that function will save.

C#
private void ExportUserstoCSV(string stringFileName)
{
    //   File FileStream1 = new System.IO.File();
    StringBuilder StringBuilder1 = new StringBuilder(null);
    foreach (string string1 in User.StringArrayUesrProperties)
    {
        if (StringBuilder1.Length == 0)
            StringBuilder1.Append(string1);
        StringBuilder1.Append(',' + string1);
    }
    StringBuilder1.AppendLine();
    foreach (User User1 in Users1)
    {
        StringBuilder StringBuilderTemp = new StringBuilder(null);
        foreach (string string1 in User1.Properties())
        {
            if (StringBuilderTemp.Length == 0)
                StringBuilderTemp.Append(string1);
            StringBuilderTemp.Append(',' + string1);
        }
        //   StringBuilder1.AppendLine();
        StringBuilder1.AppendLine(StringBuilderTemp.ToString());
    }
    File.WriteAllText(stringFileName, StringBuilder1.ToString(), Encoding.UTF8);
    MessageBox.Show("Saved Successfully", "Active Directory", 
      MessageBoxButton.OK, MessageBoxImage.Information);
}

Export computers to CSV:

C#
private void ExportComputerstoCSV(string stringFileName)
{
    //   File FileStream1 = new System.IO.File();
    StringBuilder StringBuilder1 = new StringBuilder(null);
    foreach (string string1 in Computer.StringArrayComputerProperties)
    {
        if (StringBuilder1.Length == 0)
            StringBuilder1.Append(string1);
        StringBuilder1.Append(',' + string1);
    }
    StringBuilder1.AppendLine();
    foreach (Computer Computer1 in Computers1)
    {
        StringBuilder StringBuilderTemp = new StringBuilder(null);
        foreach (string string1 in Computer1.Properties())
        {
            if (StringBuilderTemp.Length == 0)
                StringBuilderTemp.Append(string1);
            StringBuilderTemp.Append(',' + string1);
        }
        //   StringBuilder1.AppendLine();
        StringBuilder1.AppendLine(StringBuilderTemp.ToString());
    }
    File.WriteAllText(stringFileName, StringBuilder1.ToString(), Encoding.UTF8);
    MessageBox.Show("Saved Successfully", "Active Directory", 
      MessageBoxButton.OK, MessageBoxImage.Information);
}

Export Result to Excel

We can also save the results in other formats. In this part, we export results to Excel. We use the following function to convert users data to Excel document. There are three foreach in this function. In the first one, name of properties will be saved in the first row of Excel d. Then in the next two ones, for each user, all its properties will be written to Excel document. Finally, the Excel document will be saved.

C#
private void ExportUserstoExcel(string stringFileName)
{
    Excel._Application ExcelApplication;
    Excel.Workbook ExcelWorkbook;
    Excel.Worksheet ExcelWorksheet;
    object objectMisValue = System.Reflection.Missing.Value;
    Excel.Range ExcelRangeCellinstance;
    ExcelApplication = new Excel.Application();
    ExcelWorkbook = ExcelApplication.Workbooks.Add(objectMisValue);

    ExcelWorksheet = (Excel.Worksheet)ExcelWorkbook.Worksheets.get_Item(1);
    ExcelApplication.DisplayAlerts = false;
    ExcelRangeCellinstance = ExcelWorksheet.get_Range("A1", Type.Missing);
    int intRow = 1;
    int intColumn = 1;
    foreach (string string1 in User.StringArrayUesrProperties)
    {
        ExcelWorksheet.Cells[intRow, intColumn] = string1;
        intColumn++;
    }
    intRow++;
    foreach (User User1 in Users1)
    {
        intColumn = 1;
        foreach (string string1 in User1.Properties())
        {
            ExcelWorksheet.Cells[intRow, intColumn] = string1;
            intColumn++;
        }
        intRow++;
    }
    //Highlight first row
    Excel.Range ExcelRange1 = ExcelWorksheet.get_Range("A1", Type.Missing);
    ExcelRange1.EntireRow.Font.Color = 
             System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
    ExcelRange1.Interior.Color = 
             System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSkyBlue);
    ExcelRange1.EntireRow.Font.Size = 14;
    ExcelRange1.EntireRow.AutoFit();
    //Save Excel
    ExcelWorkbook.SaveAs(stringFileName, Excel.XlFileFormat.xlWorkbookNormal, 
      objectMisValue, objectMisValue, objectMisValue, objectMisValue, 
      Excel.XlSaveAsAccessMode.xlExclusive, objectMisValue, 
      objectMisValue, objectMisValue, objectMisValue, objectMisValue);
    ExcelWorkbook.Close();
    MessageBox.Show("Saved Successfully", 
      "Active Directory", MessageBoxButton.OK, MessageBoxImage.Information);
}

Export computers to Excel:

C#
private void ExportComputerstoExcel(string stringFileName)
{
    Excel._Application ExcelApplication;
    Excel.Workbook ExcelWorkbook;
    Excel.Worksheet ExcelWorksheet;
    object objectMisValue = System.Reflection.Missing.Value;
    Excel.Range ExcelRangeCellinstance;
    ExcelApplication = new Excel.Application();
    ExcelWorkbook = ExcelApplication.Workbooks.Add(objectMisValue);

    ExcelWorksheet = (Excel.Worksheet)ExcelWorkbook.Worksheets.get_Item(1);
    ExcelApplication.DisplayAlerts = false;
    ExcelRangeCellinstance = ExcelWorksheet.get_Range("A1", Type.Missing);
    int intRow = 1;
    int intColumn = 1;
    foreach (string string1 in Computer.StringArrayComputerProperties)
    {
        ExcelWorksheet.Cells[intRow, intColumn] = string1;
        intColumn++;
    }
    intRow++;
    foreach (Computer Computer1 in Computers1)
    {
        intColumn = 1;
        foreach (string string1 in Computer1.Properties())
        {
            ExcelWorksheet.Cells[intRow, intColumn] = string1;
            intColumn++;
        }
        intRow++;
    }
    //Highlight first row
    Excel.Range ExcelRange1 = ExcelWorksheet.get_Range("A1", Type.Missing);
    ExcelRange1.EntireRow.Font.Color = 
         System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
    ExcelRange1.Interior.Color = 
         System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSkyBlue);
    ExcelRange1.EntireRow.Font.Size = 14;
    ExcelRange1.EntireRow.AutoFit();
    //Save Excel
    ExcelWorkbook.SaveAs(stringFileName, Excel.XlFileFormat.xlWorkbookNormal, objectMisValue, 
      objectMisValue, objectMisValue, objectMisValue, Excel.XlSaveAsAccessMode.xlExclusive, 
      objectMisValue, objectMisValue, objectMisValue, objectMisValue, objectMisValue);
    ExcelWorkbook.Close();
    MessageBox.Show("Saved Successfully", "Active Directory", 
      MessageBoxButton.OK, MessageBoxImage.Information);
}

We add this code to export button so when user clicks on it, save dialog box will be displayed and if user decided to save the result, we send that file name to ExportExcell function.

C#
public void buttonExport_Click(object sender, RoutedEventArgs e)
{
    try
    {
        if (EnumDataGrid1 != EunmDataGrid.empty)
        {
            if (radiobuttonExcel.IsChecked == true)
            {
                Microsoft.Win32.SaveFileDialog SaveFileDialog1 = 
                                    new Microsoft.Win32.SaveFileDialog();
                SaveFileDialog1.Filter = "Excel Workbook (*.xls)|*.xls";
                if ((bool)SaveFileDialog1.ShowDialog())
                {
                    if (EnumDataGrid1 == EunmDataGrid.users)
                    {
                        ExportUserstoExcel(SaveFileDialog1.FileName);
                    }
                    else if (EnumDataGrid1 == EunmDataGrid.computers)
                    {
                        ExportComputerstoExcel(SaveFileDialog1.FileName);
                    }
                }
            }
            else
            {
                Microsoft.Win32.SaveFileDialog SaveFileDialog1 = 
                                     new Microsoft.Win32.SaveFileDialog();
                SaveFileDialog1.Filter = "Comma-Separated Value (*.csv)|*.
                    <span id="frmark_1" style="color: " + 
                    "white; font-weight: bold; background-color: highlight;">
                    <span id="frmark_1" style="color: white; " + 
                    "font-weight: bold; background-color: highlight;">csv</span></span>";
                if ((bool)SaveFileDialog1.ShowDialog())
                {
                    if (EnumDataGrid1 == EunmDataGrid.users)
                    {
                        ExportUserstoCSV(SaveFileDialog1.FileName);
                    }
                    else if (EnumDataGrid1 == EunmDataGrid.computers)
                    {
                        ExportComputerstoCSV(SaveFileDialog1.FileName);
                    }
                }
            }
        }
        else
        {
            MessageBox.Show("First click on show button", 
              "Active Directory Users", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Points of Interest

Display everything about users and computers in your domain with just a click.

History

  • 26th January, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Amazon AWS
Canada Canada
• MCSD (Microsoft Certified Solutions Developer): App Builder
• MCSD (Microsoft Certified Solutions Developer): Web Applications
• MCSA (Microsoft Certified Solutions Associate): Universal Windows Platform
• MCP (Microsoft Certified Professional)

• PMI-PBA (PMI Professional in Business Analysis)
• PMI-ACP (PMI Agile Certified Practitioner)
• PMP (Project Management Professional)

Comments and Discussions

 
NewsVote of 5 Pin
inam200112-Jul-16 1:29
inam200112-Jul-16 1:29 
GeneralMy vote of 5 Pin
lukazo22-Jun-16 23:49
lukazo22-Jun-16 23:49 
QuestionWhere to add a filter Pin
treesprite22-Jun-16 16:01
professionaltreesprite22-Jun-16 16:01 
PraiseExtremely useful piece of work Pin
kishor dhembare21-Jun-16 2:31
kishor dhembare21-Jun-16 2:31 
QuestionHow to Get all shared folders an Active Directory user has access to? Pin
Member 1239555916-Mar-16 23:07
Member 1239555916-Mar-16 23:07 
GeneralMy vote of 5 Pin
treesprite13-Jun-15 7:07
professionaltreesprite13-Jun-15 7:07 
QuestionHow to add "Extension Class" to pull additional User AD items? Pin
treesprite13-Jun-15 7:05
professionaltreesprite13-Jun-15 7:05 
Questionvs2010 pro not compatible? Pin
Aqueel Suleman24-Jan-14 4:55
Aqueel Suleman24-Jan-14 4:55 
GeneralRe: vs2010 pro not compatible? Pin
MehdiNaseri30-Jan-14 0:43
professionalMehdiNaseri30-Jan-14 0:43 
GeneralMy vote of 5 Pin
Amir Mohammad Nasrollahi7-Aug-13 21:33
professionalAmir Mohammad Nasrollahi7-Aug-13 21:33 
GeneralRe: My vote of 5 Pin
MehdiNaseri30-Jan-14 0:38
professionalMehdiNaseri30-Jan-14 0:38 
GeneralMy vote of 5 Pin
fredatcodeproject26-Feb-13 11:29
professionalfredatcodeproject26-Feb-13 11:29 
GeneralMy vote of 4 Pin
fredatcodeproject26-Jan-13 3:12
professionalfredatcodeproject26-Jan-13 3:12 
AnswerRe: My vote of 4 Pin
MehdiNaseri28-Jan-13 3:09
professionalMehdiNaseri28-Jan-13 3:09 
QuestionExport to CSV or CVS? Please clarify Pin
DrABELL25-Jan-13 19:04
DrABELL25-Jan-13 19:04 
AnswerRe: Export to CSV or CVS? Please clarify Pin
MehdiNaseri26-Jan-13 2:20
professionalMehdiNaseri26-Jan-13 2:20 
GeneralRe: Export to CSV or CVS? Please clarify Pin
DrABELL26-Jan-13 4:46
DrABELL26-Jan-13 4:46 
Suggestionmultiple Domaincontrollers Pin
Nico Patitz6-Nov-12 7:23
Nico Patitz6-Nov-12 7:23 
This source will ask the first Domaincontroller it finds in your environment. If you got a multi-DomainController-Environment you have to ask every DC for lastlogon and return the latest to get a correct resultset. (Otherwise use LastlogonTimestamp Wink | ;-) )
Great article and remembers me to have a look at the System.DirectoryServices.AccountManagement namespace Cool | :cool:

Cheers Nico
GeneralRe: multiple Domaincontrollers Pin
MehdiNaseri6-Nov-12 17:59
professionalMehdiNaseri6-Nov-12 17:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.