How to get username from Active Directory?

I want to get the login name from Active Directory.

For example, the name "Jan Van der Linden" After specifying this name as a parameter, I must return its login name, for example jvdlinden

+4
source share
5 answers

Since you are using .NET 3.5 and above, you should check the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read more here:

Managing directory security principles in the .NET Framework 3.5

Basically, you can define the context of a domain 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 very easy to play with users and groups in AD:

+5
source

using the .net library, you can use the following code to get the username or any information from the 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 (LIKE name 'ws%' or Name LIKE 'it%')" this will get the username with full name

hope this helps you

+1
source

this actually does the very opposite, but can be the starting point for checking and changing if necessary:

Search for a user in Active Directory with login

+1
source

This link needs snipple code

Confirm 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 } } } 
+1
source

No ID:

 private string GetLogonFromDisplayName(string displayName) { var search = new DirectorySearcher(string.Format("(&(displayname={0})(objectCategory=user))", displayName)); search.PropertiesToLoad.Add("sAMAccountName"); SearchResult result = search.FindOne(); if (result != null) { var logonNameResults = result.Properties["sAMAccountName"]; if (logonNameResults == null || logonNameResults.Count == 0) { return null; } return logonNameResults[0].ToString(); } return null; } 
0
source

Source: https://habr.com/ru/post/1344080/


All Articles