Checking if a user exists in a domain without enumerating through the list of users.
Recently I had to determine if a user exists in a particular group in a particular domain. Since I am not using ActiveDirectory/LDAP I couldn't use the System.DirectoryServices.DirectorySearcher (which limited my options a great deal).
I found a number of examples of people recommending that you retrieve Members Collection of a Group DirectoryEntry and then enumerating through the list. The problem with this approach is that as the list of members grows, so does the time it takes to evaluate the list. So I needed a better method. Fortunately, you can create a DirectoryEntry object and invoke one of its underlying ( COM ) methods. So, if in your DirectoryEntry construction, you specify a valid group path, you can invoke the IsMember method off of the internally contained object that implements IADsGroup.
In other words, two lines of code will enable you to determine if a user is a member of a WinNT Group. This example checks against a local group.
// Construct a DirectoryEntry object pointing to a group local to my machine ( this could be a domain group).
DirectoryEntry groupEntry = new DirectoryEntry( "WinNT://MyMachineName/MyLocalGroupName,group" );
// Now invoke the IsMember method
bool val = (bool)groupEntry.Invoke( "IsMember","WinNT://CORPORATEDOMAIN/MNolton");
As with any of my postings, feedback is appreciated.
Mathew Nolton