动态获取当前LDAP路径

本文关键字:LDAP 路径 获取 动态 | 更新日期: 2023-09-27 18:00:58

我正在用C#和.NET Framework 4.0开发一个库。

我想检索所有的active directory用户,它工作得很好。但我的问题是,如果我在另一个域上运行我的程序,我必须更改这个:

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

并使用新域的新数据重新编译它。

有什么方法可以动态获取"LDAP://DC=ic,DC=local"吗?

动态获取当前LDAP路径

几周前我也做过同样的事情。我使用了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,这对于初始化DirectorySearcher的根DirectoryEntry非常有用。

我希望这能回答你的问题,并能有所帮助。

是的,您要查找的是默认命名上下文,该信息保存在所有域通用的RootDSE上下文中:

DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
string defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value;

您应该签出System.DirectoryServices.AccountManagement(S.DS-AM(命名空间。点击此处阅读:

  • 在.NET Framework 3.5中管理目录安全主体
  • System.DirectoryServices.AccountManagement上的MSDN文档

基本上,您可以定义域上下文,并在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中与用户和组一起玩变得非常容易!