How do you look up a user in Active Directory?
Some example usernames are:
- avatopia\ian
- avatar\ian
- [email protected]
- [email protected]
- avatopia.com\ian
It's important to note that i don't know the name of the domain, and i shouldn't be hard-coding it.
There is some sample code on stack-overflow that fails.
using System.DirectoryServices;
/// <summary>
/// Gets the email address, if defined, of a user from Active Directory.
/// </summary>
/// <param name="userid">The userid of the user in question. Make
/// sure the domain has been stripped first!</param>
/// <returns>A string containing the user's email address, or null
/// if one was not defined or found.</returns>
public static string GetEmail(string userid)
{
DirectorySearcher searcher;
SearchResult result;
string email;
// Check first if there is a slash in the userid
// If there is, domain has not been stripped
if (!userid.Contains("\\"))
{
searcher = new DirectorySearcher();
searcher.Filter = String.Format("(SAMAccountName={0})", userid);
searcher.PropertiesToLoad.Add("mail");
result = searcher.FindOne();
if (result != null)
{
email = result.Properties["mail"][0].ToString();
}
}
return email;
}
It specifically ensures that you didn't pass a full username. e.g.
Bad: avatopia\ian
Bad: avatar\ian
Good: ian
Good: ian
Because you are not allowed to pass the domain, it can't differentiate between the two users
ian
ian
Another guy has the same question on sackoverflow, but the accepted answer says that you must
first locate the naming context for the required domain
i don't know what a "naming context" is, and i don't know what the "required domain" is. i'd really rather not write a regular expression to try to parse usernames into domain names and account names, e.g.
domain.something\user-name
into
domain.something
user-name
because i know there will be some edge case that i'll get wrong. i want the proper, intended, method of looking up a user in active directory.
There's a nice page on CodeProject How to do almost everything in Active Directory, but you can't lookup a user's information by username
i would hope that i can give my domain controller (whoever it is, where ever it is, whatever it's called) a username, and it will figure out which domain that user belongs to, talk to that domain controller, and get the work done.