System.DirectoryServices.AccountManagement namespace
Posted on April 8, 2008
The AccountManagement namespace is part of the .Net 3.5 framework, and provides an easy way to access and modify directory services.
I used to have my own ADHelper library that encapsulated the methods in System.DirectoryServices namespace.
Recently, i had to find out if a user was member of a specified group. This was possible, but it took a lot of lines of code. With the AccountManagement namespace it can be done in a few lines:
static void Main()
{
UserPrincipal user = UserPrincipal.Current;
if (user == null && !IsMemberOf(user, Settings.Default.EditorRole))
{
// user is found
}
}
static bool IsMemberOf(UserPrincipal user, string roleName)
{
bool result = false;
if (user != null)
{
PrincipalSearchResult groups = user.GetGroups();
if (groups != null)
{
foreach (Principal principal in groups)
{
if (principal.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))
{
result = true;
break;
}
}
}
}
return result;
}