views:

352

answers:

2

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  A: 

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.

mgroves
+1  A: 

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

marc_s