简体   繁体   English

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

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

I've been searching through the internet to learn how to interact with Active Directory. 我一直在互联网上搜索以学习如何与Active Directory进行交互。 I find the following piece of code but I want to know what ActiveDirectoryPath must be ? 我找到以下代码,但是我想知道ActiveDirectoryPath必须是什么?

Any brief description of the code is welcome 欢迎对代码进行任何简短描述

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);

Not entirely clear what you mean by detect Active Directory path - there's really no "current" AD path or anything; 通过检测Active Directory路径无法完全弄清您的意思-确实没有“当前” AD路径或其他任何内容; there's no "current directory" like in your file system. 文件系统中没有“当前目录”。

You can determine the system default path by inspecting the LDAP://RootDSE entry and looking for the defaultNamingContext there: 您可以通过检查LDAP://RootDSE条目并在此处查找defaultNamingContext来确定系统默认路径:

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

Or you can just retrieve the currently logged in user from Active Directory, and inspect it's LDAP path (this code works on .NET 3.5 and newer with the new System.DirectoryServices.AccountManagement namespace): 或者,您可以仅从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;
}

This will return the full LDAP path for the user, which contains the "container" that user is created in - something like: 这将返回用户的完整LDAP路径,其中包含在其中创建用户的“容器”-类似于:

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

and here the OU=SomeOU,DC=YourCompany,DC=Com part is the "path" in the Active Directory where this user exists inside of. 此处OU=SomeOU,DC=YourCompany,DC=Com部分是该用户所在的Active Directory中的“路径”。

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

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