Can I retrieve the domain name and user name by searching Active Directoy using C#

邮差的信 提交于 2019-12-25 01:51:09

问题


All,

I have a big list of user emails, and I need to get the username and domain name for each one of them.

My organization contains lots of domains and our users log on to their machine using usernames that are different from their email addresses.

Please advise if we can write a C# utility that can search AD using the email of each user, or if we can do it in a simpler way.


回答1:


Are you on .NET 3.5 ? If so - AD has great new features in .NET 3.5 - check out this article Managing Directory Security Principals in .NET 3.5 by Ethan Wilanski and Joe Kaplan.

One of the big new features is a "PrincipalSearcher" class which should greatly simplify finding users and/or groups in AD.

If you cannot use .NET 3.5, use a DirectorySearcher and specify the e-mail address as your search criteria, and retrieve the user name (which one? There's a gazillion different usernames!):

DirectoryEntry deRoot = new DirectoryEntry("LDAP://cn=Users,dc=yourdomain,dc=com");

DirectorySearcher deSrch = new DirectorySearcher(deRoot);

deSrch.SearchScope = SearchScope.Subtree;

deSrch.PropertiesToLoad.Add("sn");  // surname = family name
deSrch.PropertiesToLoad.Add("givenName");
deSrch.PropertiesToLoad.Add("samAccountName");

deSrch.Filter = string.Format("(&(objectCategory=person)(mail={0}))", emailAddress);

foreach(SearchResult sr in deSrch.FindAll())
{
  // you can access the properties of the search result
  if(sr.Properties["sn"] != null)
  {
     string surname = sr.Properties["sn"][0].ToString();
  }
  // and so on, for all the other properties, too
}

Hope this helps!

Marc




回答2:


If that data is all in AD, then you can probably query it using LDAP. In which case, I would recommend DirectorySearcher since you are using .NET.



来源:https://stackoverflow.com/questions/1125352/can-i-retrieve-the-domain-name-and-user-name-by-searching-active-directoy-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!