2009-09-04 2 views

答えて

4

.NET 3.5にはありますか?

このような場合は、この優れたMSDN記事Managing Directory Security Principals in the .NET Framework 3.5を参照してください。これは、.NET 3.5のユーザー管理とグループ管理の新機能を示しています。

このケースでは、主要なコンテキスト(例えば、ドメイン)が必要です。

PrincipalContext domainContext = 
    new PrincipalContext(ContextType.Domain, "YourDomain"); 

をして、あなたはかなり簡単にユーザーを見つけることができます:

UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username"); 

と「のUserPrincipal」オブジェクトがあります

PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups(); 

// display the names of the groups to which the 
// user belongs 

foreach (Principal result in results) 
{ 
    Console.WriteLine("name: {0}", result.Name); 
} 

P:すべてのグループにユーザを戻す「GetAuthorizationGroups」と呼ばれる方法は、以下のメンバーでありますリティーは簡単?

これは.NET 3.5より前のほうがはるかに多く、他の言語(PHP、Delphiなど)の「ストレート」LDAPではもっと多くの作業があります。ここで

マルク・

+0

素晴らしい作品です!本当にありがとう。 – Donut

1

は、グループ情報を取得する別の方法です:

あなたはSystem.DirectoryServicesのための参照を追加していることを確認します。

DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar"); 

DirectoryEntry user = GetObjectBySAM("SomeUserName", root); 

if (user != null) 
{ 
    foreach (string g in GetMemberOf(user)) 
    { 
    Console.WriteLine(g); 
    } 
} 

次のメソッドは、ユーザーエントリを取得し、ユーザーが所属するグループである文字列のリストを返します。

public List<string> GetMemberOf(DirectoryEntry de) 
{ 
    List<string> memberof = new List<string>(); 

    foreach (object oMember in de.Properties["memberOf"]) 
    { 
    memberof.Add(oMember.ToString()); 
    } 

    return memberof; 
} 

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root) 
{ 
    using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam))) 
    { 
    SearchResult sr = searcher.FindOne(); 

    if (!(sr == null)) return sr.GetDirectoryEntry(); 
    else 
     return null; 
    } 
}