我正在使用 .Net 库的 System.DirectoryServices.AccountManagement 部分连接到 ActiveDirectory。
在 GroupPrincipal 对象上调用 GetMembers() 并过滤结果后,我现在有了 UserPrincipal 对象的集合
GroupPrincipal myGroup; // population of this object omitted here
foreach (UserPrincipal user in myGroup.GetMembers(false).OfType<UserPrincipal>())
{
Console.WriteLine(user.SamAccountName);
}
上面的代码示例将打印出像“TestUser1”这样的用户名。我需要将这些与来自另一个应用程序的“DOMAIN\TestUser1”格式的列表进行比较。
如何从 UserPrincipal 对象中获取“DOMAIN”部分?
我不能只附加一个已知域名,因为涉及多个域,我需要区分 DOMAIN1\TestUser1 和 DOMAIN2\TestUser2。
最佳答案
你有两个我能想到的选择。
- 解析或获取
name@fully.qualified.domain.name
右侧的所有内容; - 使用
System.DirectoryServices
命名空间。
我不了解 UserPrincipal,也不了解 GroupPrincipal。另一方面,我知道一种可以实现您想要的目标的有效方法。
[TestCase("LDAP://fully.qualified.domain.name", "TestUser1")]
public void GetNetBiosName(string ldapUrl, string login)
string netBiosName = null;
string foundLogin = null;
using (DirectoryEntry root = new DirectoryEntry(ldapUrl))
Using (DirectorySearcher searcher = new DirectorySearcher(root) {
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("sAMAccountName");
searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", login);
SearchResult result = null;
try {
result = searcher.FindOne();
if (result == null)
if (string.Equals(login, result.GetDirectoryEntry().Properties("sAMAccountName").Value))
foundLogin = result.GetDirectoryEntry().Properties("sAMAccountName").Value
} finally {
searcher.Dispose();
root.Dispose();
if (result != null) result = null;
}
}
if (!string.IsNullOrEmpty(foundLogin))
using (DirectoryEntry root = new DirectoryEntry(ldapUrl.Insert(7, "CN=Partitions,CN=Configuration,DC=").Replace(".", ",DC="))
Using DirectorySearcher searcher = new DirectorySearcher(root)
searcher.Filter = "nETBIOSName=*";
searcher.PropertiesToLoad.Add("cn");
SearchResultCollection results = null;
try {
results = searcher.FindAll();
if (results != null && results.Count > 0 && results[0] != null) {
ResultPropertyValueCollection values = results[0].Properties("cn");
netBiosName = rpvc[0].ToString();
} finally {
searcher.Dispose();
root.Dispose();
if (results != null) {
results.Dispose();
results = null;
}
}
}
Assert.AreEqual("INTRA\TESTUSER1", string.Concat(netBiosName, "\", foundLogin).ToUpperInvariant())
}
此 SO 问题中提供的其他相关信息或链接。
C# Active Directory: Get domain name of user?
How to find the NetBIOS name of a domain
关于c# - 从 UserPrincipal 对象获取 nETBIOSName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4284641/