我有一个代码来获取用户所属的组。
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个本地组的一部分。
请帮助解决这个谜团。感谢
研究
我做了一些调查,并得知我正在返回域用户的主要群组
称为“域用户”组
但我真正想要的是域用户所属的本地机器组......我无法得到...任何建议
使用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;
}
这也有效,但我得到了相同的结果“域用户”。请一些人告诉我如何获得本地机器组... ????
答案 0 :(得分:2)
如果您使用的是.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);
}
答案 1 :(得分:0)
我想说问题是你的搜索是从域名开始的。您想将搜索位置更改为本地计算机。
像这样的东西会这样做;
DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");