Monday, August 24, 2009

Accessing Active Directory through C#.Net

If you are reading from an office computer, you might have already been logged in to a domain using your domain user id and password. Most of the organizations use Active Directory (AD) to organize their internal computing assets and also control access to it. Have you ever used an intranet website that greets with your full name (without logging in)? System.DirectoryServices name space in .Net gives access to AD services and allows us to do lot of things.


To see the current logged in account details,

string DomainUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Replace("\\", "/");

To get the full name of the currently logged in user,

DirectoryEntry ADEntry = new DirectoryEntry("WinNT://" + DomainUser);
string FullName = ADEntry.Properties["FullName"].Value.ToString();

And if you want to loop through all the available resources in AD,

foreach (string propName in ADEntry.Properties.PropertyNames)
{
foreach (object value in ADEntry.Properties[propName])
{
Response.Write( propName + " : "+ value.ToString() + " : " + value.GetType() + "\n");
}
}

This introduction will only help have a glance at AD. You could do a lot more if you explore the AD and System.DirectoryService name space.

No comments: