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