I found several sample on Stackoverflow and over the web but any work. I'd like to check is a user is member of a specific group (or subgroup). When I try with a username who not exist in the Active Directiory, I get an Exception (normal, see the code)
Below the current code I use :
using System;
using System.DirectoryServices;
using System.Collections.Generic;
static class Program
{
public static string GetUserContainerName(string userName)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxx:389/DC=be,DC=kb,DC=int");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = string.Format("(&(sAMAccountName={0}))", userName);
mySearcher.SearchScope = SearchScope.Subtree; //Search from base down to ALL children.
SearchResultCollection result = mySearcher.FindAll();
if (result.Count == 0)
throw new ApplicationException(string.Format("User '{0}' Not Found in Active Directory.", userName));
return result[0].GetDirectoryEntry().Name.Replace("CN=", string.Empty);
}
public static bool IsUserMemberOfGroup(string username, string groupname)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxx.be.kb.int:389/DC=be,DC=kb,DC=int");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = string.Format(String.Format("(member:1.2.840.113556.1.4.1941:=(cn={0},cn=users,DC=be,DC=kb,DC=int))", username), GetUserContainerName(username));
mySearcher.SearchScope = SearchScope.Subtree; //Search from base down to ALL children.
SearchResultCollection result = mySearcher.FindAll();
for (int i = 0; i < result.Count - 1; i++)
{
if (result[i].Path.ToUpper().Contains(string.Format("CN={0}", groupname.ToUpper())))
return true; //Success - group found
}
return false;
}
static void Main(string[] args)
{
var res = IsUserMemberOfGroup("MyUSer", "MY_GROUP_TO_CHECK");
Console.WriteLine(res.ToString());
}
}