动态获取当前的LDAP路径

动态获取当前的LDAP路径

本文介绍了动态获取当前的LDAP路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing a library with C# and .NET Framework 4.0.

我要检索所有Active Directory用户和它的伟大工程。但我的问题,如果我在另一个域中运行我的节目,我必须改变这一点:

I want to retrieve all active directory users and it works great. But my problem if I run my program on another domain I have to change this:

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

和与新域新的数据重新编译。

And recompile it with the new data for the new domain.

有没有什么办法让LDAP:// DC = IC,DC =本地?动态

推荐答案

我几个星期前做同样的事情。我使用了 System.DirectoryServices.ActiveDirectory 库,并使用 DomainController 的对象找到你所期待的。

I've done the exact same thing few weeks ago. I used the System.DirectoryServices.ActiveDirectory library, and used the Domain and DomainController objects to find what you are looking for.

下面是code我使用:

Here is the code I'm using:

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 ,一切都被初始化一次(避免资源泄漏)或域名等。或者ROOTPATH​​,这是初始化根非常有用的的DirectoryEntry DirectorySearcher从

And then, You simply call DomainManager.DomainPath, everything is initialized once (it avoids resource leaks) or DomainName and so on. Or RootPath, which is very useful to initialize the root DirectoryEntry for DirectorySearcher.

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

I hope this answers your question and could help.

这篇关于动态获取当前的LDAP路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:51