Searching for a user in AD in .NET 3.5
.NET 3.5 brought with it the new System.DirectoryServices.AccountManagement namespace, which makes working with Active Directory so much easier. Let's take a look at how to find a user if you know their username (SAMAccountName):
private static UserPrincipal GetPrincipal(string name)
{
var context = new PrincipalContext(
ContextType.Domain, "yourdomain.com");
var principal = UserPrincipal.FindByIdentity(
context, IdentityType.SamAccountName, name);
return principal;
}
Wow, three entire lines of code. I don't know how we'll ever convince anyone to switch from the old way of doing things. :-) How about getting the user's groups?
PrincipalSearchResult<Principal> GetGroups(UserPrincipal principal)
{
return principal.GetAuthorizationGroups();
}
How about you just want to dump properties about that principal?
private static IDictionary<string, string> GetProperties(UserPrincipal principal)
{
var properties = new Dictionary<string, string>();
var directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
var allProperties = directoryEntry.Properties;
foreach (var property in allProperties.PropertyNames)
{
var propertyName = property.ToString();
var value = string.Empty;
if (allProperties[propertyName] != null && allProperties[propertyName].Count > 0)
{
foreach (var val in allProperties[propertyName])
{
if (val != null)
{
value += ", " + val.ToString();
}
}
}
properties.Add(property.ToString(), value);
}
return properties;
}