簡體   English   中英

如何獲得所有Active Directory用戶的用戶名和顯示名稱

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

我有一個使用ASP.Net MVC 5的Intranet應用程序

我需要查詢所有Active Directory用戶的用戶名

我在網上搜索了2條有用的文章:1- 如何從活動目錄中獲取用戶列表?

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

查詢時,我可以獲取Name屬性,但無法獲取活動目錄用戶名

我可以獲取所有Active Directory用戶用戶名的任何解決方案?

下面是我的代碼:

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


        }

您要查找的屬性名稱是sAMAccountName 這是可用屬性的列表。

我這樣做的方式非常有效:

1-添加對Active Directory服務DLL的引用

2-在您的控制器中添加使用:

 using System.DirectoryServices.AccountManagement;

比我創建了一個將所有Active Directory用戶存儲在數據庫表中的功能,下面的代碼是希望幫助某人需要的代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM