C
Chris Noble
I need to check whether a particular user is already a member of an Active
Directory Security Group.
The following code extract works but only if the user distinguished name is
exactly the same as that returned from Active Directory. For example using
'cn=' in the userdn string instead of 'CN=' does not work.
As far as I am aware Active Directory is not case sensitive and it is
therefore difficult to predict the case of a string.
Before I write code to extract all the strings (converted into either upper
or lower case) into a sorted list to be able to search for the user is there
a way to make the Contains method work more predictably?
The ResultPropertyValueCollection (result.Properties["member"]) contains
objects of type String.
DirectoryEntry parententry = new DirectoryEntry(LDAPParentPath);
DirectoryEntry groupentry = parententry.Children.Find(user.Group);
DirectorySearcher ds = new DirectorySearcher(groupentry);
SearchResult result;
ds.PropertiesToLoad.Add("member");
result = ds.FindOne();
if (result != null)
{
String userdn = String.Format("CN={0},{1}", user.User_logon_name,
user.Ldap_container);
if (!result.Properties["member"].Contains(userdn)) // NB Case Sensitive
{
// add user to group
groupentry.Properties["member"].Add(userdn);
groupentry.CommitChanges();
}
}
Directory Security Group.
The following code extract works but only if the user distinguished name is
exactly the same as that returned from Active Directory. For example using
'cn=' in the userdn string instead of 'CN=' does not work.
As far as I am aware Active Directory is not case sensitive and it is
therefore difficult to predict the case of a string.
Before I write code to extract all the strings (converted into either upper
or lower case) into a sorted list to be able to search for the user is there
a way to make the Contains method work more predictably?
The ResultPropertyValueCollection (result.Properties["member"]) contains
objects of type String.
DirectoryEntry parententry = new DirectoryEntry(LDAPParentPath);
DirectoryEntry groupentry = parententry.Children.Find(user.Group);
DirectorySearcher ds = new DirectorySearcher(groupentry);
SearchResult result;
ds.PropertiesToLoad.Add("member");
result = ds.FindOne();
if (result != null)
{
String userdn = String.Format("CN={0},{1}", user.User_logon_name,
user.Ldap_container);
if (!result.Properties["member"].Contains(userdn)) // NB Case Sensitive
{
// add user to group
groupentry.Properties["member"].Add(userdn);
groupentry.CommitChanges();
}
}