Radical Development

Technical Without the Technicalities

Active Directory C# Code Snippets

An active directory (sometimes referred to as an AD) does a variety of functions including the ability to provide information on objects, helps organize these objects for easy retrieval and access, allows access by end users and administrators and allows the administrator to set security up for the directory. Should you find yourself needing to interface with active directory via a C# application the following snippets may prove useful.

Retrieving objects from Active Directory

public static List GetAllObjects(string DN, List properties, bool useRecursion)
{
var results = new List();

var dates = new List()
{
"pwdLastSet",
"badPasswordCountTime",
"lastLogoff",
"lastLogon",
"lastLogonTimestamp",
"lockoutTime"
};

try
{
DirectoryEntry de = new DirectoryEntry("LDAP://" + DN);
foreach (DirectoryEntry child in de.Children)
{

if (child.Properties.Contains("ou"))
{
if (useRecursion) results.AddRange(GetAllObjects(child.Path.Remove(0, 7), properties, useRecursion));
}
else
{
var propertySb = new StringBuilder();

var lcounter = 0;

foreach (var property in properties)
{
var val = "";
if (child.Properties.Contains(property))
{
if(dates.Contains(property))
{
var t = child.Properties[property].Value;
var ticks = GetInt64(child, property);
var dateFormattedValue = DateTime.FromFileTime(ticks);
val = dateFormattedValue.ToString();
}
else
{
val = child.Properties[property].Value.ToString();
}

if (val != property)
{
if (lcounter + 1 == properties.Count)
{
propertySb.Append(val);
}
else
{
propertySb.Append(val + ",");
}
}
}

lcounter++;
}

results.Add(propertySb.ToString());
}

child.Close();
child.Dispose();
}

de.Close(); de.Dispose();

}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

return results;
}

Get Members of an Active Directory Distribution Group

public SortedList GetUsersInGroup(string domain, string group)
{
SortedList groupMemebers = new SortedList();

string sam = "";
string fname = "";
string lname = "";
string active = "";

DirectoryEntry de = new DirectoryEntry("LDAP://DC=" + domain + ",DC=com");

DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=person)");
ds.Filter = "(memberOf=CN=" + group + ",OU=Distribution Groups,DC=" + domain + ",DC=com)";

ds.PropertiesToLoad.Add("givenname");
ds.PropertiesToLoad.Add("samaccountname");
ds.PropertiesToLoad.Add("sn");
ds.PropertiesToLoad.Add("useraccountcontrol");

foreach (SearchResult sr in ds.FindAll())
{
try
{
sam = sr.Properties["samaccountname"][0].ToString();
fname = sr.Properties["givenname"][0].ToString();
lname = sr.Properties["sn"][0].ToString();
active = sr.Properties["useraccountcontrol"][0].ToString();
}
catch (Exception e)
{
}

// don't grab disabled users
if (active.ToString() != "514")
{
groupMemebers.Add(sam.ToString(), (fname.ToString() + " " + lname.ToString()));
}
}

return groupMemebers;
}