动态获取当前LDAP路径

时间:2014-04-30 08:33:05

标签: c# windows active-directory

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

我想检索所有活动目录用户,但效果很好。但我的问题是,如果我在另一个域上运行我的程序,我必须改变它:

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

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

有没有办法动态获取"LDAP://DC=ic,DC=local"

3 个答案:

答案 0 :(得分:4)

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

我希望这能回答你的问题并提供帮助。

答案 1 :(得分:3)

是的,您正在寻找的是默认的命名上下文,该信息保存在RootDSE上下文中,这对所有域都是通用的:

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

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

答案 2 :(得分:0)

您应该查看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中的用户和群组一起玩!