我正在尝试列出给定用户所属的所有组,并且我想支持本地计算机帐户和域帐户。我可以使用以下代码获取域帐户的组:
public void ListAllGroupsDomain()
{
ListAllGroups(ContextType.Domain,
"myDomain",
"myDomainUser",
"myDomainPassword");
}
public void ListAllGroups(ContextType contextType
string name,
string username,
string password)
{
using (var context = new PrincipalContext(contextType,
name,
username,
password))
{
using (var findByIdentity = UserPrincipal.FindByIdentity(context, "testedit"))
{
if (findByIdentity != null)
{
var groups = findByIdentity.GetGroups(context);
var results = groups.Select(g => g.Name).ToArray();
Console.WriteLine("Listing {0} groups", results.Count());
foreach (var name in results)
{
Console.WriteLine("{0}", name);
}
}
}
}
}
但是,如果我尝试调用本机的本地帐户,我会收到一个COM异常,说我的用户名或密码不正确(它们不是):
public void ListAllGroupsMachine()
{
ListAllGroups(ContextType.Machine,
"myMachine",
"myMachineUser",
"myMachinePassword");
}
我猜我正在为机器帐户错误地使用FindByIdentity。所以我尝试了一种不同的方法,不使用FindByIdentity:
public void ListAllGroups2(ContextType contextType
string name,
string username,
string password)
{
using (var context = new PrincipalContext(contextType,
name,
username,
password))
{
using (var userContext = new UserPrincipal(context))
{
var results = userContext.GetGroups();
Console.WriteLine("Listing {0} groups:", results.Count());
foreach (var principal in results)
{
Console.WriteLine("{0}", principal.Name);
}
}
}
}
此版本没有抛出任何异常,但对GetGroups()
的调用也未返回任何结果。如何获取特定用户所属的组对于计算机和域帐户都可靠?
答案 0 :(得分:4)
感谢我从https://stackoverflow.com/a/3681442/1222122收集的一些帮助,我弄清楚我做错了什么。我错误地设置了PrincipalContext。我不需要提供域名,用户名或密码,只需要提供ContextType。以下代码适用于本地计算机帐户和域帐户:
public void ListAllGroupsDomain()
{
ListAllGroups(ContextType.Domain, "myDomainUsername");
}
public void ListAllGroupsMachine()
{
ListAllGroups(ContextType.Machine, "myMachineUsername");
}
public void ListAllGroups(ContextType contextType, string userName)
{
using (var context = new PrincipalContext(contextType))
{
using (var findByIdentity = UserPrincipal.FindByIdentity(context, userName))
{
if (findByIdentity != null)
{
var groups = findByIdentity.GetGroups(context);
var results = groups.Select(g => g.Name).ToArray();
Console.WriteLine("Listing {0} groups", results.Count());
foreach (var name in results)
{
Console.WriteLine("{0}", name);
}
}
}
}
}
我唯一需要做的就是在将域名传递给ListAllGroups
之前从用户名中删除域名,因为提供给我的函数会在某些情况下将其添加到用户名中