我有一个代码来获取用户所属的组。
try
{
DirectoryEntry adRoot = new DirectoryEntry(string.Format("WinNT://{0}", Environment.UserDomainName));
DirectoryEntry user = adRoot.Children.Find(completeUserName, "User");
object obGroups = user.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
// Create object for each group.
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
listOfMyWindowsGroups.Add(obGpEntry.Name);
}
return true;
}
catch (Exception ex)
{
new GUIUtility().LogMessageToFile("Error in getting User MachineGroups = " + ex);
return false;
}
当我必须找到本地用户的组时,上面的代码工作正常但是
对于域用户,它返回一个值“域用户”,这有点奇怪,因为它是 2 个本地组的一部分。
请有人帮忙解开这个谜团。谢谢
Research
我做了一些发现并得到我返回域用户的主要组
称为“域用户”组
但我真正想要的是域用户所属的本地计算机组......我无法得到......任何建议
another code using LDAP
string domain = Environment.UserDomainName;
DirectoryEntry DE = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
DirectorySearcher search = new DirectorySearcher();
search.SearchRoot = DE;
search.Filter = "(SAMAccountName=" + completeUserName + ")"; //Searches active directory for the login name
search.PropertiesToLoad.Add("displayName"); // Once found, get a list of Groups
try
{
SearchResult result = search.FindOne(); // Grab the records and assign them to result
if (result != null)
{
DirectoryEntry theUser = result.GetDirectoryEntry();
theUser.RefreshCache(new string[] { "tokenGroups" });
foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
{
System.Security.Principal.SecurityIdentifier mySID = new System.Security.Principal.SecurityIdentifier(resultBytes, 0);
DirectorySearcher sidSearcher = new DirectorySearcher();
sidSearcher.SearchRoot = DE;
sidSearcher.Filter = "(objectSid=" + mySID.Value + ")";
sidSearcher.PropertiesToLoad.Add("distinguishedName");
SearchResult sidResult = sidSearcher.FindOne();
if (sidResult != null)
{
listOfMyWindowsGroups.Add((string)sidResult.Properties["distinguishedName"][0]);
}
}
}
else
{
new GUIUtility().LogMessageToFile("no user found");
}
return true;
}
catch (Exception ex)
{
new GUIUtility().LogMessageToFile("Error obtaining group names: " + ex.Message + " Please contact your administrator."); // If an error occurs report it to the user.
return false;
}
这也有效,但我得到相同的结果“域用户”。请有人告诉我如何获得本地机器组...????
最佳答案
如果您使用的是 .NET 3.5,则可以使用 System.DirectoryService.AccountManagement做所有的用户和组管理。特别是,UserPrincipal.GetAuthorizationGroups正是您要寻找的。它为特定用户检索本地组和机器组。如果该组是本地组,则 GroupPrincipal.Context.Name 显示该组所在的计算机名称。如果该组是域组,则 GroupPrincipal.Context.Domain 显示该组来自的域名。
PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com");
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "youruser");
foreach (GroupPrincipal group in userPrincipal.GetAuthorizationGroups())
{
Console.Out.WriteLine("{0}\\{1}", group.Context.Name, group.SamAccountName);
}
关于c# - 获取本地组而不是域用户的主要组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475889/