DotNet Programming World

Thursday, November 10, 2011

Get Active Directory User Entry


public static DirectoryEntry GetAdUserEntry(this SPUser user)
{
try
{
var path = "LDAP://DC=[domain name without .com],DC=Corp,DC=net";

if (!string.IsNullOrEmpty(user.LoginName))
{
var userId = user.LoginName.ToUpper().Replace("[ntdomain name]\\", "");
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", userId);

var properties = new string[] { "fullname" };
var searchRoot = new DirectoryEntry(path, "[domain userid]", "[password]");

var search = new DirectorySearcher(searchRoot);

search.SearchScope = SearchScope.Subtree;
search.ReferralChasing = ReferralChasingOption.All;
search.PropertiesToLoad.AddRange(properties);
search.Filter = filter;
SearchResult result = search.FindOne();

if (result != null)
{
DirectoryEntry directoryEntry = result.GetDirectoryEntry();
return directoryEntry;
}
}
}
catch (Exception ex)
{
return null;
}

return null;
}

0 Comments:

Post a Comment

<< Home