我有一个代码来检查用户是否是组的成员。我在登录时使用它。
请注意我有一个域用户和本地用户,例如。testdomain\administrator
和administrator
。
这是我使用的代码:
using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./" + userGroupName + ",group"))
{
foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
{
using (DirectoryEntry memberEntry = new DirectoryEntry(member))
{
string completeName = memberEntry.Name;
DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
if (domainValue != null)
{
completeName = domainValue.Name + "\\" + memberEntry.Name;
}
Global.logger.Info("completeName from " + userGroupName + " = " + completeName);
if (userName.Equals(completeName, StringComparison.InvariantCultureIgnoreCase))
{
Global.logger.Debug("IsUserPartOfWindowsGroup returned True with username =" + userName + " , UserGroupName = " + userGroupName);
return true;
}
}
}
Global.logger.Debug("IsUserPartOfWindowsGroup returned false for username =" + userName + " , UserGroupName = " + userGroupName);
return false;
}
此代码有效,但
DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
正如我所见,在分析器中花费了很多时间。有没有更好/更快的方法来处理这个问题?
public static DirectoryEntry FindDomain(DirectoryEntry memberEntry)
{
if (memberEntry.Parent != null)
{
if (memberEntry.Parent.SchemaClassName.Equals("domain", StringComparison.InvariantCultureIgnoreCase))
{
return memberEntry.Parent;
}
}
return null;
}
另一种方式:
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, Password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
SearchResult result = mySearcher.FindOne();
Global.logger.Info("result == " + result.Path);
foreach (string GroupPath in result.Properties["memberOf"])
{
if (GroupPath.Contains(adminGroupName))
{
Global.logger.Info(compUsrNameForEncryption + "exists in " + adminGroupName);
}
}