How to retrieve login name of a user from Active Directory?

10,541

Solution 1

Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5

Basically, you can define a domain context and easily find users and/or groups in AD:

public string GetLoginName(string userName)
{
  // set up domain context
  PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

  // find user by name
  UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);

  if(user != null)
       return user.SamAccountName;
  else
       return string.Empty;
}

The new S.DS.AM makes it really easy to play around with users and groups in AD:

Solution 2

using .net library you can use the following code to get username or any info from active directory

using System.Management;
using System.Management.Instrumentation;
using System.Runtime.InteropServices;
using System.DirectoryServices;

ManagementObjectSearcher Usersearcher = new ManagementObjectSearcher("Select * From Win32_ComputerSystem Where (Name LIKE 'ws%' or Name LIKE 'it%')"); 
            ManagementObjectCollection Usercollection = Usersearcher.Get(); 
            string[] sep = { "\\" };
            string[] UserNameDomain = Usercollection.Cast<ManagementBaseObject>().First()["UserName"].ToString().Split(sep, StringSplitOptions.None);

i add "Select * From Win32_ComputerSystem Where (Name LIKE 'ws%' or Name LIKE 'it%')" this will get the user name by the full name

hope this could help you

Solution 3

this actually does almost the opposite but can be a starting point to check and modify as needed:

Finding a User in Active Directory with the Login Name

Solution 4

Check this link has needed code snipple

Validate AD-LDAP USer

using (DirectoryEntry entry = new DirectoryEntry())
        {
            entry.Username = "DOMAIN\\LOGINNAME";
            entry.Password = "PASSWORD";
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = "(objectclass=user)";
            try
            {
                searcher.FindOne();
                {
                    //Add Your Code if user Found..
                }
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2147023570)
                {
                    ex.Message.ToString();
                    // Login or password is incorrect 
                }
            }
        }
Share:
10,541
Tassisto
Author by

Tassisto

Specialized in software developing using .NET Technologies.

Updated on June 08, 2022

Comments

  • Tassisto
    Tassisto almost 2 years

    I want to retrieve the login name of a user from Active Directory.

    For example the name is 'Jan Van der Linden' After giving this name as parameter I must get his login name in return for example jvdlinden