public static DataTable SearchADUsers(string userName)
{
using (DataTable dtUsers = new DataTable())
{
dtUsers.Locale = CultureInfo.InvariantCulture;
dtUsers.Columns.Add("key");
dtUsers.Columns.Add("value");
foreach (string domainToBeSearched in ConfigurationDetails.DomainTobeChecked.Split(','))
{
ValidateADUser(domainToBeSearched, userName, dtUsers);
}
return dtUsers;
}
}
private static void ValidateADUser(string domainToBeSearched, string userName, DataTable dtUsers)
{
try
{
using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainToBeSearched))
{
using (DirectorySearcher searcher = new DirectorySearcher())
{
searcher.SearchRoot = domain;
searcher.Filter = FormFilter("user", userName + "*");
searcher.SearchScope = SearchScope.Subtree;
searcher.PageSize = 10;
using (SearchResultCollection adResult = searcher.FindAll())
{
DataRow dtrUsers = null;
foreach (SearchResult result in adResult)
{
if (dtUsers.Select("key='" + result.Properties["samaccountname"][0].ToString() + "'").Length <= 0)
{
dtrUsers = dtUsers.NewRow();
dtrUsers[0] = result.Properties["samaccountname"][0].ToString();
dtrUsers[1] = result.Properties["DisplayName"][0];
dtUsers.Rows.Add(dtrUsers);
}
}
}
}
}
}
catch (Exception ex)
{
LogUtil.WriteLog(LogLevel.ERROR, ex.ToString());
}
}
Specify the domain names in config file
<add key="DomainTobeChecked" value="abc.com, lmn.com,xyz.net">