簡體   English   中英

使用 PrincipalContext 連接到活動目錄

[英]Connect to active directory with PrincipalContext

我是根據名稱在活動目錄中查找用戶的書面應用程序

當我嘗試使用 ContextType.Domain 和域名作為字符串創建新的 PrincipalContext 時,出現異常“無法聯系服務器”。

因此,為了獲得我執行的 AD... 打開系統,方法是單擊“開始”按鈕“開始”按鈕的圖片、“控制面板”、“系統和維護”,然后單擊“系統”。 我從http://windows.microsoft.com/en-gb/windows-vista/find-the-domain-your-computer-is-on得到的

這給了我Something.Something(不是這個,而是兩個字符串,它們之間有一個 . )

因此,當我運行以下代碼並輸入Something.Something 作為域時,我收到異常“無法聯系服務器”。 在新的 PrincipalContext(ContextType.Domain, domain) 上; 我曾嘗試更改字符串的大小寫,但似乎沒有任何運氣。

那么我應該為域使用什么?

    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Enter Domain, then press enter.");
            string domain = Console.ReadLine();

            Console.WriteLine("Enter First Name, then press enter.");
            string userName = Console.ReadLine();

            //This is the line that always crashes throws error
            var principalContext = new PrincipalContext(ContextType.Domain, domain);
            var user = UserPrincipal.FindByIdentity(principalContext, userName);

            if (user == null)
            {
                Console.WriteLine("User Not Found");
            }

            var groups = user.GetGroups(principalContext);
            var result = new List<string>();
            groups.ToList().ForEach(sr => result.Add(sr.SamAccountName));

            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

Ashley 是正確的...假設您在加入域的機器上運行應用程序。

using System;
using System.DirectoryServices.AccountManagement;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter First Name, then press enter.");
            var userName = Console.ReadLine();

            // Will search the domain the application is running on
            var principalContext = new PrincipalContext(ContextType.Domain);
            var user = UserPrincipal.FindByIdentity(principalContext, userName);

            if (user == null)
            {
                Console.WriteLine("User Not Found");
            }
            else
            {
                // Gets a list of the user's groups
                var groups = user.GetGroups().ToList();

                // Loops the groups and prints the SamAccountName
                groups.ForEach(g => Console.WriteLine(g.SamAccountName));
            }

            Console.ReadKey();
        }
    }
}

如果您有幾秒鍾的時間等待來自大型 AD 的數據,請繼續使用 PrincipalContext,但如果您希望以毫秒為單位進行響應,請使用 DirectoryEntry、DirectorySearcher 和 .PropertiesToLoad。

以下是獲取用戶組的示例:

https://stackoverflow.com/a/65986796/5248400

暫無
暫無

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

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