我有代码来获取本地组示例管理员的成员
private void GetUserGrps()
{
using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
{
foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
{
using (DirectoryEntry memberEntry = new DirectoryEntry(member))
{
new GUIUtility().LogMessageToFile(memberEntry.Path);
}
}
}
有没有办法让本地用户所属的组使用目录服务?
不使用Active Directory或域,因为我只想要本地计算机而不是域。
答案 0 :(得分:5)
试试这个
using System.DirectoryServices.AccountManagement;
static void Main(string[] args)
{
ArrayList myGroups = GetUserGroups("My Local User");
}
public static ArrayList GetUserGroups(string sUserName)
{
ArrayList myItems = new ArrayList();
UserPrincipal oUserPrincipal = GetUser(sUserName);
PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
foreach (Principal oResult in oPrincipalSearchResult)
{
myItems.Add(oResult.Name);
}
return myItems;
}
public static UserPrincipal GetUser(string sUserName)
{
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
return oUserPrincipal;
}
public static PrincipalContext GetPrincipalContext()
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);
return oPrincipalContext;
}