Grh*_*rhm 12 .net c# active-directory userprincipal
我正在使用.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);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码示例将打印出"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())
}
Run Code Online (Sandbox Code Playgroud)
此 SO 问题中提供的其他相关信息或链接。
C# Active Directory:获取用户的域名?
如何查找域的 NetBIOS 名称