Scenario
Sometimes we may need to get the domain account name from the directory where we give the display name as input.
Code
using System.Text.RegularExpressions;
using System.DirectoryServices;
public static string GetDomainAccountName(string displayName)
{
DirectoryEntry entry = new DirectoryEntry();
entry.Path = "GC://domain.self.com/dc=hi,dc=self,dc=com";
entry.AuthenticationType = AuthenticationTypes.Secure;
entry.Username = "me\\username";
entry.Password = "password";
string[] fullName = displayName.Split(','); //name in format LastName, Firstname
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = string.Format("(&(objectClass=user)(objectCategory=Person)(&(givenName={0})(sn={1})))", fullName[1].Trim(), fullName[0].Trim());
search.PropertiesToLoad.Add("mail"); // Email Address
search.PropertiesToLoad.Add("givenName"); // First Name
search.PropertiesToLoad.Add("sn"); // Last Name
search.PropertiesToLoad.Add("l"); // City
search.PropertiesToLoad.Add("st"); // State
search.PropertiesToLoad.Add("co"); // Country
search.PropertiesToLoad.Add("postalCode"); // PostalCode
search.PropertiesToLoad.Add("SAMAccountName"); //AccountName
search.PropertiesToLoad.Add("distinguishedName"); //DomainName
// Search for the specified user.
SearchResult result = search.FindOne();
if (result != null) // User found
{
string userEmailAddress = GetProperty(result, "mail");
string userFirstName = GetProperty(result, "givenName");
string userLastName = GetProperty(result, "sn");
string userCity = GetProperty(result, "l");
string userState = GetProperty(result, "st");
string userCountry = GetProperty(result, "co");
string userPostalCode = GetProperty(result, "postalCode");
string userName = GetProperty(result, "SAMAccountName");
string userD = GetProperty(result, "distinguishedName");
Regex regex = new Regex("(?<=DC=).+?(?=,)");
Match match = regex.Match(userD);
string domain = match.Groups[0].Value;
return domain + "\\" + userName;
}
return string.Empty;
}
public static string GetProperty(DirectoryEntry searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString().ToLower();
}
else
{
return string.Empty;
}
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
Thanks
No comments:
Post a Comment