Какую версию .NET Framework вы можете использовать? Поиск и поиск информации в AD стал чрезвычайно легким в .NET 3.5 - посмотрите эту замечательную статью MSDN , написанную Итаном Вилански и Джо Капланом об использовании API участников безопасности.
Если вы еще не используете .NET 3.5, вам придется использовать класс DirectorySearcher
и настроить фильтры поиска так, как вам нужно. Правильный выбор фильтра LDAP, вероятно, является самым большим препятствием.
У Робби Аллена также есть две замечательные вступительные статьи о программировании System.DirectoryServices:
- Часть 1
- часть 2
Есть несколько действительно хороших ресурсов на http://www.directoryprogramming.net (сайт Джо Каплана - он MVP Microsoft Active Directory), и у Ричарда Мюллера есть несколько отличных справочных листов Excel о том, какие свойства доступны для каждого из поставщиков ADSI, и что они имеют в виду, и как называется их LDAP - см. http://www.rlmueller.net.
Марк
РЕДАКТИРОВАТЬ: Хорошо, вот подход .NET 2.0 / 3.0:
// set the search root - the AD container to search from
DirectoryEntry searchRoot = new DirectoryEntry("LDAP://dc=yourdomain,dc=com");
// create directory searcher
DirectorySearcher ds = new DirectorySearcher(searchRoot);
ds.SearchScope = SearchScope.Subtree;
// set the properties to load in the search results
// the fewer you load, the better your performance
ds.PropertiesToLoad.Add("cn");
ds.PropertiesToLoad.Add("sn");
ds.PropertiesToLoad.Add("givenName");
ds.PropertiesToLoad.Add("mail");
// set the filter - here I'm using objectCategory since this attribute is
// single-valued and indexed --> much better than objectClass in performance
// the "anr" is the "ambiguous name resolution" property which basically
// searches for all normally interesting name properties
ds.Filter = "(&(objectCategory=person)(anr=user-name-here))";
// get the result collection
SearchResultCollection src = ds.FindAll();
// iterate over the results
foreach (SearchResult sr in src)
{
// do whatever you need to do with the search result
// I'm extracting the properties I specified in the PropertiesToLoad
// mind you - a property might not be set in AD and thus would
// be NULL here (e.g. not included in the Properties collection)
// also, all result properties are really multi-valued, so you need
// to do this trickery to get the first of the values returned
string surname = string.Empty;
if (sr.Properties.Contains("sn"))
{
surname = sr.Properties["sn"][0].ToString();
}
string givenName = string.Empty;
if (sr.Properties.Contains("givenName"))
{
givenName = sr.Properties["givenName"][0].ToString();
}
string email = string.Empty;
if (sr.Properties.Contains("mail"))
{
email = sr.Properties["mail"][0].ToString();
}
Console.WriteLine("Name: {0} {1} / Mail: {2}", givenName, surname, email);
}
Надеюсь, это поможет!
Марк