Click here to Skip to main content
Click here to Skip to main content

Active Directory Users and Computers

, 26 Jan 2013
Rate this:
Please Sign up or sign in to vote.
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 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:

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 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.

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:

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.

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.

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 as specific groups for example domain admins. In this situation can select that group. Also if you enter a password then only users who have the same password will be displayed.

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

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.

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.

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:

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 following function to convert users data to Excel document. There are three foreach in this function. In first one, name of properties will be saved in first row of Excel d. Then in next two ones, for each user, all it's properties will be written to excel document. finally the excel document will be saved.

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:

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.

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-Seprated 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.

License

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

Share

About the Author

MehdiNaseri
Chief Technology Officer National Iranian Oil Company (NIOC)
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
- Timeline of my career focus:
1994: Batch files in Microsoft Dos
1995: GW-Basic, Q Basic
1996: Assembly, C
1999: Pascal, C++
2000: Bachelor of Science Degree in Computer Software Engineering
2001: Borland Delphi, Microsoft SQL Server, HTML
2002: Visual Basic, C--, Ada, Lisp, Prolog, JavaScript
2003: C#, Java
2004: Asp.net, Computer Networks
2005: Master of Science Degree in Computer Software Engineering
2006: Data Mining
2007: XML, XQuery, XSLT
2008: WPF
2009: Silverlight, Network Administration
2010: ASP.NET MVC, JQuery, CSS, Ajax, LINQ, Entity Framework
2011: VMware Visualization (vSphere, vCenter)
2012: Microsoft SharePoint, Microsoft System Center, Microsoft Visualization (Hyper-V), Microsoft Exchange Server, Microsoft Lync, Windows 8 App
2013: Cloud Computing (VMware and Microsoft Hyper-V), Microsoft Project Server.
2014: ???

Comments and Discussions

 
Questionvs2010 pro not compatible? PinmemberAqueel Suleman24-Jan-14 4:55 
GeneralRe: vs2010 pro not compatible? PinmemberMehdiNaseri30-Jan-14 0:43 
GeneralMy vote of 5 PinprofessionalAmir Mohammad Nasrollahi7-Aug-13 21:33 
GeneralRe: My vote of 5 PinmemberMehdiNaseri30-Jan-14 0:38 
GeneralMy vote of 5 Pinmemberfredatcodeproject26-Feb-13 11:29 
GeneralMy vote of 4 Pinmemberfredatcodeproject26-Jan-13 3:12 
AnswerRe: My vote of 4 PinmemberMehdiNaseri28-Jan-13 3:09 
QuestionExport to CSV or CVS? Please clarify PinmemberDrABELL25-Jan-13 19:04 
AnswerRe: Export to CSV or CVS? Please clarify PinmemberMehdiNaseri26-Jan-13 2:20 
GeneralRe: Export to CSV or CVS? Please clarify PinmemberDrABELL26-Jan-13 4:46 
Suggestionmultiple Domaincontrollers PinmemberNico Patitz6-Nov-12 7:23 
GeneralRe: multiple Domaincontrollers [modified] PinmemberMehdiNaseri6-Nov-12 17:59 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 26 Jan 2013
Article Copyright 2012 by MehdiNaseri
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid