2
我想列出给定用户所属的所有用户组,并且我想同时支持本地计算机帐户和域帐户。我可以用下面的代码获取域帐户组:获取用户属于本地和域帐户的用户组
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()
也没有返回任何结果。如何获得特定用户所属的组对于机器和域帐户都是可靠的?
这正是我要找的atm,但是我对访问.FindByIdentity和.GetGroups调用的速度非常慢。您是否遇到过这方面的性能问题? – Spikeh
Spikeh对你来说有多慢?我在做这件事时尝试了几种不同的方法,而且我似乎记得有些东西几乎是瞬间的,有些则需要10秒以上。但是,这么长时间以来,我无法告诉你更多的东西。 – Gillfish
FindByIdentity大约需要4秒(使用ContextType.Machine),GetGroups大约需要6秒。我不在域上,但是 - Windows 8.1,通过IISExpress运行。一些缓存时间,methinks。 – Spikeh