Using the following code I can easily see if the supplied user exists in a supplied group.
public static bool IsInGroup(string user, string group)
{
using (var identity = new WindowsIdentity(user))
{
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(group);
}
}
However, given a list of strings like the following:-
User1
User2
User3
Group1
Group2
Group3
Is there any way in c# by looping this list of strings, to check to see if each entry is an AD group or not ?
For example, User3 is actually a group name, but from looking at the list you would think it’s a normal AD user.
Is there any way of parsing the name to see if it exists as a group on my AD domain.
I basically want to be able to run through a list of names and groups, and see if a given user name (for example ‘Bob’) is in the list, or exists in one of the groups in this list, therefore if an entry in the list above is an AD group I want to run a function similar to above to see if the user exists within the group or not.
It isn’t too bad. You will need to reference the following Assemblies:
Then you can use something like this:
You can change out the PrincipalContext constructor to use ContextType.Machine for the local machine, and if needed you can add the domain name as a second parameter, but for a local domain it should pick it up.
[edit] Also, the FindByIdentity method will return null if it doesn’t match. Also, you can get member users and other useful information from the Directory Services.