簡體   English   中英

動態獲取當前LDAP路徑

[英]Get current LDAP Path dynamically

我正在使用C#和.NET Framework 4.0開發一個庫。

我想檢索所有活動目錄用戶,它很好用。 但我的問題是,如果我在另一個域上運行我的程序,我必須改變這個:

private static string ldapPath = "LDAP://DC=ic,DC=local";

並使用新域的新數據重新編譯它。

有沒有辦法動態獲取"LDAP://DC=ic,DC=local"

我幾周前完成了同樣的事情。 我使用了System.DirectoryServices.ActiveDirectory庫,並使用DomainDomainController對象來查找您要查找的內容。

這是我正在使用的代碼:

public static class DomainManager
{
    static DomainManager()
    {
        Domain domain = null;
        DomainController domainController = null;
        try
        {
            domain = Domain.GetCurrentDomain();
            DomainName = domain.Name;
            domainController = domain.PdcRoleOwner;
            DomainControllerName = domainController.Name.Split('.')[0];
            ComputerName = Environment.MachineName;
        }
        finally
        {
            if (domain != null)
                domain.Dispose();
            if (domainController != null)
                domainController.Dispose();
        }
    }

    public static string DomainControllerName { get; private set; }

    public static string ComputerName { get; private set; }

    public static string DomainName { get; private set; }

    public static string DomainPath
    {
        get
        {
            bool bFirst = true;
            StringBuilder sbReturn = new StringBuilder(200);
            string[] strlstDc = DomainName.Split('.');
            foreach (string strDc in strlstDc)
            {
                if (bFirst)
                {
                    sbReturn.Append("DC=");
                    bFirst = false;
                }
                else
                    sbReturn.Append(",DC=");

                sbReturn.Append(strDc);
            }
            return sbReturn.ToString();
        }
    }

    public static string RootPath
    {
        get
        {
            return string.Format("LDAP://{0}/{1}", DomainName, DomainPath);
        }
    }
}

然后,您只需調用DomainManager.DomainPath ,一切都初始化(它避免資源泄漏)或DomainName等。 或者ROOTPATH,這是非常有用的初始化根DirectoryEntryDirectorySearcher

我希望這能回答你的問題並提供幫助。

是的,您正在尋找的是默認的命名上下文,該信息保存在RootDSE上下文中,這對所有域都是通用的:

DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");

string defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value;

您應該檢查System.DirectoryServices.AccountManagement (S.DS.AM)命名空間。 在這里閱讀所有相關內容:

基本上,您可以定義域上下文並輕松查找AD中的用戶和/或組:

// set up domain context - uses the current domain you're connected to
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }
}

新的S.DS.AM使得在AD中與用戶和群組玩游戲變得非常容易!

暫無
暫無

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

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