Find an AD Group in a Forest?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
OK... For some reason, if an AD Group resides on a different domain, using the Current.User.IsInRole("GroupName") will not return true even if the user is in the group. So I wrote a function to look at the domain containing the AD Group using LDAP queries.
Below is my 100% working code:try
{
SearchResult _UserSearchResult = default(SearchResult);
using (DirectoryEntry _UserDirectoryEntry = new DirectoryEntry(string.Format("LDAP://{0}", Domain.GetCurrentDomain().Name)))
{
using (DirectorySearcher _UserDirectorySearcher = new DirectorySearcher(_UserDirectoryEntry))
{
_UserDirectorySearcher.Filter = string.Format("(sAMAccountName={0})", _User);
_UserSearchResult = _UserDirectorySearcher.FindOne();
}
}

string _DirectoryString = "LDAP://abc.xyz.com";
DirectoryEntry _DirectoryEntry = new DirectoryEntry(_DirectoryString);
DirectorySearcher _DirectorySearcher = new DirectorySearcher(_DirectoryEntry);
string _SearchStringGroup = string.Format("(&(objectCategory=group)(sAMAccountName={0}))", _GroupName);

_DirectorySearcher.SearchScope = SearchScope.Subtree;
_DirectorySearcher.Filter = _SearchStringGroup.ToString();
_DirectorySearcher.PropertiesToLoad.Add("distinguishedname");

foreach (SearchResult _SecurityGroup in _DirectorySearcher.FindAll())
{
string[] _UserData = _UserSearchResult.Path.ToString().Split(/);
DirectoryEntry _Entry = _SecurityGroup.GetDirectoryEntry();
foreach (string _Member in _Entry.Properties["member"])
{
if (_Member == _UserData[_UserData.Length - 1]) { return true; }
}
}

return false;
}
catch { return false; }
}

Unfortunately, I want to make this into more modular code. I am willing to sacrifice speed if it means I can make it more "drag and drop". Now since an AD Group can exist in multiple domains within a single forest, is there anyway to get a list of all the domains within the forest that the AD Group is in?
Please, I am content with the above code and have tried everything Google would throw at me until I hacked together this block and got the result I was looking for. So please, do not try to change my code, rather address my question.

View the full article
 
Back
Top