从PrincipalContext查找域组件

Eri*_*len 2 c# directoryservices active-directory

我正在尝试使用PrincipalContext通过Active Directory服务找出域组件。

我使用很少的参数创建了PrincipalContext:

PrincipalContext theContext = new PrincipalContext(ContextType.Domain);
Run Code Online (Sandbox Code Playgroud)

theContext正确返回。我可以查询很多东西并获得预期的结果。但是我真正想做的是:

Console.WriteLine("Domain Component: " + theContext.Container);
Run Code Online (Sandbox Code Playgroud)

根据MSDN,这仅“获取在构造函数中的容器参数中指定的值”。既然我什么都没传递,我什么也得不到。

但是理论上的容器具有域组件,您可能需要使用或创建的任何专有名称都需要这些域组件。我特别希望在一个已知的组织单位中创建一个新用户。但是,由于我不知道域组件,因此无法创建专有名称。我还没有看到对相对路径的任何支持。

我认为最好的选择是搜索任何用户,然后获取其专有名称并删去“ dc”部分。

var searchUser = new UserPrincipal(theContext);
var searcher = new PrincipalSearcher(searchUser);
Principal aUser = searcher.FindOne();
if (aUser != null)
{
    string dn = aUser.DistinguishedName;
    Console.WriteLine(dn.Substring(dn.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase)));

}
Run Code Online (Sandbox Code Playgroud)

感觉像是一个糟糕的骇客。太多可能会出错。我希望有更好的东西。有人有主意吗?

Har*_*wok 5

为了获得命名上下文,您应该绑定到RootDSE。RootDSE提供了目录服务器的许多有用信息。在所有这些defaultNamingContext属性中,attribute存储所需的域专有名称。

要绑定到当前登录用户的域的RootDSE,可以使用无服务器绑定。要在当前登录的用户域的RootDSE上进行无服务器绑定,绑定字符串应如下所示

LDAP://RootDSE
Run Code Online (Sandbox Code Playgroud)

这是您可以使用的方式 DirectoryEntry

DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
string domainContext = rootDSE.Properties["defaultNamingContext"].Value as string;
Run Code Online (Sandbox Code Playgroud)