如何从AD DirectoryEntry获取DOMAIN\USER?

lak*_*tak 15 .net c# active-directory

如何从Active Directory DirectoryEntry(SchemaClassName ="user")对象获取Windows用户和域?

用户名在sAMAccountName属性中,但在哪里可以查找域名?

(我不能假设一个固定的域名,因为用户来自不同的子域名.)

小智 25

这假设results是从DirectorySearcher获取的SearchResultCollection,但您应该能够直接从DirectoryEntry获取objectsid.

SearchResult result = results[0];
var propertyValues = result.Properties["objectsid"];
var objectsid = (byte[])propertyValues[0];

var sid = new SecurityIdentifier(objectsid, 0);

var account = sid.Translate(typeof(NTAccount));
account.ToString(); // This give the DOMAIN\User format for the account
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这对我不起作用 - 我有对象,但我在Translate()调用上得到了一个IdentityNotMappedException.这可能是因为运行代码的机器不是域的一部分,我只是查询AD. (3认同)

mar*_*c_s 7

遗憾的是,您无法在DirectoryEntry中找到您要查找的内容.

你有sAMAccountName通常的东西myuser(没有域名).你有distinguishedName这样的东西LDAP://cn=joe myuser,cn=Users,dc=yourCompany,dc=com.你也有一个,userPrincipalName但通常是格式的名称joeUser@mycompany.com.

domain\MyUser不幸的是,你找不到任何包含它的属性.您必须将有关域名的信息和DirectoryEntry的sAMAccountName放在一起.

有关System.DirectoryServices中所有LDAP和WinNT属性的更多信息和一些优秀的Excel表格,请访问ADSI MVP Richard Mueller 的Hilltop Lab网站.


小智 7

要获取DirectoryEntry域名,您可以使用递归 directoryEntry.Parent.然后,如果directoryEntry.SchemaClassName == "domainDNS" 你能得到这样的域名:

directoryEntry.Properties["Name"].Value
Run Code Online (Sandbox Code Playgroud)


lak*_*tak 4

我在 CN=Partitions,CN=Configuration 中找到了一个包含所有域的分区容器。

当您将用户与分区匹配时,您可以从 nETBIOSName+"\"+sAMAccountName 属性中读取真实域名。