繁体   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