I have a Web API method that returns the Active Directory security groups for the specific login user. The below code was working fine but it was taking so munch time nearly 45 sec to get the results.
DirectoryEntry root = GetDirectoryEntry()
using (var groups = root.Children.Find("OU=Sample Security Groups"))
{
using (var directory = groups.Children.Find("OU=Permissions"))
{
using (var searcher = new DirectorySearcher(directory))
{
searcher.Filter = `filter condition`
var results = searcher.FindAll();
foreach (SearchResult result in results)
{
if (result != null)
{
using (DirectoryEntry group = result.GetDirectoryEntry())
{
items.Add((string)group.Properties["sAMAccountName"].Value);
}
}
}
}
}
}
Update: In the GetDirectoryEntry
method we are creating the connection to the active directory using the username and password.
Can anyone help to optimize the code using Parallel.ForEach
or threading etc..
GetDirectoryEntry()
method as well. \$\endgroup\$ – Heslacher Oct 17 '19 at 4:05