Assuming that active directory is set up correctly, I’m trying to find a way to determine whether or not two people are from the same location. The only way I was able to wrap my head around it is to find a way to determine whether or not their directory entry was located in the same OU. So currently, this is what I am spit-balling at the moment:
private bool ComparePeople()
{
var user1Guid = "aaa";
var user2Guid = "bbb";
var expr = @"CN=.*?,";
var user1OU = Regex.Replace(GetUserDN(user1Guid), expr, string.Empty);
var user2OU = Regex.Replace(GetUserDN(user2Guid), expr, string.Empty);
return user1OU == user2OU;
}
private string GetUserDN(string userGuid)
{
using(var entry = new DirectoryEntry(string.format("LDAP://<GUID={0}>", userGuid)))
{
using(var search = new DirectorySearcher(entry))
{
search.PropertiesToAdd.Add("distinguishedName");
var result = search.FindOne().GetDirectoryEntry();
if(result != null && result.Properties["distinguishedName"].Count > 0)
{
return result.Properties["distinguishedName"].Value.ToString();
}
else return "";
}
}
}
I haven’t tested this yet, but I feel like it would work. It basically finds the distinguished name of a user, give their Guid. Then it removes the CN from the DN, essentially finding the path to that user’s directory entry/OU. However, it seems a bit convoluted. Does anyone have any comments or recommendations to simplify this?
If I understand you correctly, you’re trying to find out whether two user accounts are located inside the same OU (organizational unit) – right?
What I would do is read the parent of both user accounts – if that parent matches, then they’re in the same OU.
If you’re on .NET 3.5 and up, you should check out the
System.DirectoryServices.AccountManagement(S.DS.AM) namespace. Read all about it here:Basically, you can define a domain context and easily find users and/or groups in AD:
The new S.DS.AM makes it really easy to play around with users and groups in AD!