Created
March 19, 2015 16:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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