You may need to add some of the Win form controls to view the data, but the code is as follows
————————Code———————–
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.DirectoryServices;
namespace ActivedirectoryInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable dt;
string searchType = “(objectClass=person)”;
private void button1_Click(object sender, EventArgs e)
{
using (DirectoryEntry de = new DirectoryEntry(
{
DirectorySearcher LdapSearcher = new DirectorySearcher(de,(searchType));
LdapSearcher.PropertiesToLoad.Add(“displayName”);
LdapSearcher.PropertiesToLoad.Add(“cn”);
LdapSearcher.PropertiesToLoad.Add(“department”);
LdapSearcher.PropertiesToLoad.Add(“title”);
LdapSearcher.PropertiesToLoad.Add(“sn”); // surname = last name
LdapSearcher.PropertiesToLoad.Add(“givenname”); // given (or first) name
LdapSearcher.PropertiesToLoad.Add(“mail”);//Email Id
LdapSearcher.PropertiesToLoad.Add(“mailnickname”);//UserId
SearchResultCollection src = LdapSearcher.FindAll();
int i = 0;
dt = CreateSearchData();
foreach (SearchResult res in src)
{
i++;
ResultPropertyCollection fields = res.Properties;
DataRow dr= dt.NewRow();
foreach (String ldapField in fields.PropertyNames)
{
//System.Diagnostics.Debug.WriteLine(string.Format(“{0}:{1}—Count:{2}”, ldapField, fields[ldapField][0].ToString(), fields[ldapField].Count.ToString()));
CheckField(ldapField);
dr[ldapField] = fields[ldapField][0].ToString();
}
AddDataRow(dr);
//System.Diagnostics.Debug.WriteLine(“———————————————”);
}
}
dataGridView1.DataSource = dt;
label1.Text = “Count:” + dt.Rows.Count;
}
private void CheckField(string ldapField)
{
if (!dt.Columns.Contains(ldapField))
{
DataColumn column;
column = new DataColumn();
column.ColumnName = ldapField;
dt.Columns.Add(column);
}
}
public DataTable CreateSearchData()
{
DataTable dt = new DataTable(“UserData”);
DataColumn column;
column = new DataColumn();
column.ColumnName = “title”;
dt.Columns.Add(column);
column = new DataColumn();
column.ColumnName = “department”;
dt.Columns.Add(column);
column = new DataColumn();
column.ColumnName = “cn”;
dt.Columns.Add(column);
column = new DataColumn();
column.ColumnName = “displayname”;
dt.Columns.Add(column);
return dt;
}
private void AddDataRow(DataRow dr)
{
dt.Rows.Add(dr);
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
searchType = “(objectClass=person)”;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
searchType = “(objectClass=user)”;
}
}
}