Tuesday, 11 November 2014

Get User Email from Active Directory

public String GetUserEmail(string UserName)
{
try
{
string strpath = _LdapPath;
DirectoryEntry ou = new DirectoryEntry(strpath, _AdminUserName, _AdminPassword);
DirectorySearcher ds = new DirectorySearcher(ou);
String[] strArray = UserName.Split('\\');
if (strArray.Length > 1)
UserName = strArray[1];
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "User", UserName);
ds.Filter = filter;
SearchResult result = ds.FindOne();
DirectoryEntry directoryEntry = result.GetDirectoryEntry();
if (directoryEntry.Properties["mail"] != null)
return Convert.ToString(directoryEntry.Properties["mail"].Value);
return "";
}
catch (Exception ex)
{
LogErrors(ex, "GetUserEmail");
return null;
}
}
view raw gistfile1.cs hosted with ❤ by GitHub