0

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() });


        }
Community
  • 1
  • 1
MJ X
  • 8,506
  • 12
  • 74
  • 99

2 Answers2

0

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

christophano
  • 915
  • 2
  • 20
  • 29
0

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();
    }
MJ X
  • 8,506
  • 12
  • 74
  • 99