How can I search Active Directory by username using C#?

后端 未结 5 1780
名媛妹妹
名媛妹妹 2021-01-05 03:53

I\'m trying to search active directory by the username \'admin\'. I know for a fact that there is a user with that username in the directory, but the search keeps coming bac

5条回答
  •  太阳男子
    2021-01-05 04:06

    this should work

    private void showUsers(string pUserName)
        {
            string uid = Properties.Settings.Default.uid;
            string pwd = Properties.Settings.Default.pwd;
            using (var context = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", uid, pwd))
            {
                using (UserPrincipal user = new UserPrincipal(context))
                {
                    user.SamAccountName = pUserName;
                    using (var searcher = new PrincipalSearcher(user))
                    {
                        foreach (var result in searcher.FindAll())
                        {
                            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
                            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
                            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
                            Console.WriteLine("Mail: " + de.Properties["mail"].Value);
    
                            PrincipalSearchResult groups = result.GetGroups();
    
                            foreach (Principal item in groups)
                            {
                                Console.WriteLine("Groups: {0}: {1}", item.DisplayName, item.Name);
                            }
                            Console.WriteLine();
                        }
                    }
                }
            }
            Console.WriteLine("End");
            Console.ReadLine();
        }
    

提交回复
热议问题