简体   繁体   中英

How can I get all Active Directory Users username and display name

I have an Intranet application using ASP.Net MVC 5

I need to query all Active directory users username

I searched the net I found 2 useful post: 1- How can I get a list of users from active directory?

2- http://www.codeproject.com/Tips/599697/Get-list-of-Active-Directory-users-in-Csharp

When I query I can get the Name property but I can't get the active directory usernames

any solutions that I can get all Active directory users username?

bellow is my code:

        List<TempUsers> MyTempUser = new List<TempUsers>();

        var context = new PrincipalContext(ContextType.Domain, "MyDomain.com");
        var searcher = new PrincipalSearcher(new UserPrincipal(context));

        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
            MyTempUser.Add(new TempUsers { UserName = de.Properties["Name"].Value.ToString() });


        }

The property name you're looking for is sAMAccountName . Here's a list of the available attributes.

I did it this way it worked great:

1- Add reference to Active Directory services DLL

2- Add using in your controller:

 using System.DirectoryServices.AccountManagement;

than I created a function to store All Active directory users in database table bellow is the code hope help someone needs it.

    public ActionResult Create()
    {


        List<MyADUsers> TheAllADUsers = new List<MyADUsers>();

        var context = new PrincipalContext(ContextType.Domain, "MyDoman.org");
        var searcher = new PrincipalSearcher(new UserPrincipal(context));

        foreach (var result in searcher.FindAll())
        {

            TheAllADUsers.Add(new MyADUsers { ADUserName = result.SamAccountName, AD_IsMemberOf = result.UserPrincipalName, FullName = result.Name });

        }

        db.MyADUsersContext.AddRange(TheAllADUsers);
        db.SaveChanges();


        return View();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM