【发布时间】:2013-04-17 05:41:16
【问题描述】:
我正在尝试列出给定用户所属的所有组,并且我希望同时支持本地计算机帐户和域帐户。我可以使用以下代码获取域帐户的组:
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()的调用也没有返回任何结果。如何获取特定用户所属的组对于机器和域帐户都是可靠的?
【问题讨论】:
标签: c# account-management