Get email address from active directory username in C#

* Add reference to System.DirectoryServices

static string GetMail(string user)
{
  using (var connection = new DirectoryEntry())
  {
    using (var search = new DirectorySearcher(connection)
      {
        Filter = "(samaccountname=" + user + ")",
        PropertiesToLoad = {"mail"},
      })
    {
      return (string) search.FindOne().Properties["mail"][0];
    }
  }
}

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#