July 10, 2009

UserName without AD domain in C#

Someone asked in one of the forums recently can you get the username for someone in AD using C# without the domain addition. So if you have a logon name of test@mydomain.com or domain.com\test...how can you get just test?

This is actually quite easy and can be done like this:
private string ExtractPureUsername(string username)
{
string[] parts = username.Split('@');
if (parts.Length == 2)
{
return parts[0];
}

parts = username.Split('\\');
if (parts.Length == 2)
{
return parts[1];
}

return username;
}
So now you can simply write:
username = ExtractPureUsername(username);
Having brought up the topic of AD and C#, I think I'll start to share some samples next week of how to work with AD using C#.

2 comments:

  1. If you are using the System.DirectoryServices.DirectorySearcher to look up an account in AD, to get just the login name sans any domain information, you would just need the samaccountname property from the returned DirectoryEntry object.

    ReplyDelete
  2. Correct and that is what I suggested (sort of). The actual case was more of a basic regex issue where the user was to login to a site using domain\username and upon logging in they needed to parse that and search by sAMAccountName to change password. So basically...

    public void SetPass(string username, string password)
    {
    username = ExtractPureUserName(username)
    //get root OU path
    //use DirectorySearcher with the rootpath, username) and then call NativeObject.SetPassword and .SetInfo
    }

    So yes, DirectorySearcher was the way to go and this was more of a regex to get to that point based off this users specific question.

    ...I guess I should really change the title of this post :)

    ReplyDelete