Get User Info from Active Directory using LDAP
using log4net;
using System.DirectoryServices;
public class ADUserInfo
{
public string ShortName { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
}
The following method returns ADUser information:[Serializable]
[DataObject(true)]
public class ADUtilities
{
private static readonly ILog log = LogManager.GetLogger(typeof(ADUtilities));
///
/// Returns UserInfo Object,
/// Which contains User Display Name,Email Address
///
/// User ShortName
public static List< ADUserInfo> GetCurrentUserInfo(string _userName)
{
if (String.IsNullOrEmpty(_userName))
{
log.Error("UserName is null or Empty for GetCurrentUserInfo[_userName]: " + _userName);
return null;
}
try
{
string ldapqry = ConfigurationManager.AppSettings["ADConnctionstr"].ToString(); //@"LDAP://DC01.eng.stclocal";
string qryFilterFormat = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", _userName);
SearchResult result = null;
using (DirectoryEntry root = new DirectoryEntry(ldapqry))
{
using (DirectorySearcher searcher = new DirectorySearcher(root))
{
List< ADUserInfo> userInfo = new List<InfiniaUserInfo>();
ADUserInfo objuser = new InfiniaUserInfo();
searcher.Filter = qryFilterFormat;
SearchResultCollection results = searcher.FindAll();
result = (results.Count != 0) ? results[0] : null;
objuser.ShortName = (string) result.Properties["sAMAccountName"][0];
objuser.DisplayName = (string)result.Properties["displayname"][0];
if(!String.IsNullOrEmpty((string)result.Properties["mail"][0]))
objuser.Email = (string)result.Properties["mail"][0];
//else
//objuser.Email = (string)result.Properties["sAMAccountName"][0];
userInfo.Add(objuser);
return userInfo;
}
}
}
catch (Exception ex)
{
log.Error("Error to getting Email Address for GetCurrentUserEmail [username] : " + _userName + " Error Message: " + ex.Message.ToString());
return null;
}
}
}
Comments