Skip to content

Instantly share code, notes, and snippets.

@compustar
Created March 19, 2015 16:29
Show Gist options
  • Select an option

  • Save compustar/f835b6a183800194a137 to your computer and use it in GitHub Desktop.

Select an option

Save compustar/f835b6a183800194a137 to your computer and use it in GitHub Desktop.
Search domain account name (sAMAccountName) with first name and last name from AD
public static string GetSAMAccountName(string firstName, string lastName, string domain) {
string result = string.Empty;
string connectionPrefix = "LDAP://" + domain;
using (DirectoryEntry entry = new DirectoryEntry(connectionPrefix))
using (DirectorySearcher searcher = new DirectorySearcher(entry)) {
searcher.Filter = string.Format("(&(objectClass=user)(&(sn={1})(givenName={0})))", firstName, lastName);
SearchResult searchResult = searcher.FindOne();
if (searchResult == null) {
throw new NullReferenceException(string.Format("unable to locate the user {0} {1} in the {2} domain", firstName, lastName, domain));
}
DirectoryEntry directoryObject = searchResult.GetDirectoryEntry();
result = directoryObject.Properties["sAMAccountName"].Value as string;
entry.Close();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment