繁体   English   中英

如何在C#中检测Active Directory路径

[英]How to detect Active Directory path in c#

我一直在互联网上搜索以学习如何与Active Directory进行交互。 我找到以下代码,但是我想知道ActiveDirectoryPath必须是什么?

欢迎对代码进行任何简短描述

DirectoryEntry entry = new DirectoryEntry(ActiveDirectoryPath);
DirectorySearcher search = new DirectorySearcher(entry);

search.Filter = String.Format("(&(objectCategory=group)(cn={0}))", activeDirectoryGroup);
search.PropertiesToLoad.Add("distinguishedName");
SearchResult searchResult = search.FindOne();

if (searchResult == null)
    return new HashSet<User>();

DirectoryEntry group = searchResult.GetDirectoryEntry();
Hashtable searchedGroups = new Hashtable();
return GetUsersInGroup(group.Properties["distinguishedName"].Value.ToString(), searchedGroups, path);

通过检测Active Directory路径无法完全弄清您的意思-确实没有“当前” AD路径或其他任何内容; 文件系统中没有“当前目录”。

您可以通过检查LDAP://RootDSE条目并在此处查找defaultNamingContext来确定系统默认路径:

using (DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE"))
{
    if (deRoot.Properties["defaultNamingContext"] != null)
    {
        string defaultNamingContext = 
               deRoot.Properties["defaultNamingContext"].Value.ToString();
    }
}

或者,您可以仅从Active Directory中检索当前登录的用户,并检查其LDAP路径(此代码适用于.NET 3.5及更高版本(具有新的System.DirectoryServices.AccountManagement命名空间)):

using System.DirectoryServices.AccountManagement;

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
     UserPrincipal currentUser = UserPrincipal.Current;
     string userLdapPath = currentUser.DistinguishedName;
}

这将返回用户的完整LDAP路径,其中包含在其中创建用户的“容器”-类似于:

LDAP://CN=User Name,OU=SomeOU,DC=YourCompany,DC=Com

此处OU=SomeOU,DC=YourCompany,DC=Com部分是该用户所在的Active Directory中的“路径”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM