How to check if a user is member of a specific group with C#

The following code will find out if a specific user is member of a specific group in the Active Directory.

static void Main(string[] args)
{
	string group = "LDAP://cn=sales,ou=groups,ou=west,dc=contoso,dc=com";
	string member = "LDAP://cn=Jim Smith,ou=users,ou=west,dc=contoso,dc=com";

	Console.WriteLine("Determining if " + member + " is a member of the " + group + " Group...");

	using (DirectoryEntry deMember = new DirectoryEntry(member),
						  deGroup = new DirectoryEntry(group))
	{
		bool isGroupMember = (bool)deGroup.Invoke("IsMember", new object[] { deMember.Path });
		Console.WriteLine(member + (isGroupMember ? " is" : " is not") + " a member of the " + group + " Group...");
	}
}

Speak Your Mind

*