2009-07-24 27 views
4

私はActive Directoryのユーザーアカウントを管理するアプリケーションを開発中です。可能な限りSystem.DirectoryServices.AccountManagement名前空間を使用していますが、ユーザーのプライマリグループを決定する方法を理解できません。ユーザーのプライマリグループであるグループを削除しようとすると例外が発生します。ここに私の現在のコードは次のとおりです。C#でActive Directoryユーザーのプライマリグループを見つけることはできますか?

private void removeFromGroup(UserPrincipal userPrincipal, GroupPrincipal groupPrincipal) { 
    TODO: Check to see if this Group is the user's primary group. 
    groupPrincipal.Members.Remove(userPrincipal); 
    groupPrincipal.Save(); 
} 

は、私は、このグループからユーザーを削除しようとする前に、いくつかの検証を行うことができますので、ユーザーのプライマリグループの名前を取得する方法はありますか?

答えて

0

ユーザーのプライマリグループのRIDは、ユーザーオブジェクトの「primaryGroupID」属性に格納されます。この値を取得するには、指定されたユーザー(または他のユーザーのAPI)のDirectoryEntryを取得する必要があります。その値を取得した後、それをプライマリグループのSIDに変換してから、そのグループを取得する必要があります。

より、この上の詳細だけでなく、ここでは、プライマリグループを見つける方法とVBのコードを持っているKBの記事があります:http://support.microsoft.com/kb/297951

5

これはかなり厄介と関わっビジネスだ - しかし、このコードスニペットはからです私は(.NET 1.1日)C#で完全に書いて動作することが知られている私のBeaverTail ADSIブラウザ - かわいいが、機能していない:

private string GetPrimaryGroup(DirectoryEntry aEntry, DirectoryEntry aDomainEntry) 
{ 
    int primaryGroupID = (int)aEntry.Properties["primaryGroupID"].Value; 
    byte[] objectSid = (byte[])aEntry.Properties["objectSid"].Value; 

    StringBuilder escapedGroupSid = new StringBuilder(); 

    // Copy over everything but the last four bytes(sub-authority) 
    // Doing so gives us the RID of the domain 
    for(uint i = 0; i < objectSid.Length - 4; i++) 
    { 
     escapedGroupSid.AppendFormat("\\{0:x2}", objectSid[i]); 
    } 

    //Add the primaryGroupID to the escape string to build the SID of the primaryGroup 
    for(uint i = 0; i < 4; i++) 
    { 
     escapedGroupSid.AppendFormat("\\{0:x2}", (primaryGroupID & 0xFF)); 
     primaryGroupID >>= 8; 
    } 

    //Search the directory for a group with this SID 
    DirectorySearcher searcher = new DirectorySearcher(); 
    if(aDomainEntry != null) 
    { 
     searcher.SearchRoot = aDomainEntry; 
    } 

    searcher.Filter = "(&(objectCategory=Group)(objectSID=" + escapedGroupSid.ToString() + "))"; 
    searcher.PropertiesToLoad.Add("distinguishedName"); 

    return searcher.FindOne().Properties["distinguishedName"][0].ToString(); 
} 

・ホープ、このことができます。

マルク・

+1

すごいです。醜いしかしそれは働く:) +1 – Simon

+1

はい..それは働いている.. –

-2
 using (PrincipalContext context = XXX) 
     { //get the group 
       using (GroupPrincipal groupPrincipal = 
         GroupPrincipal.FindByIdentity(context,IdentityType.SamAccountName, group)) 
       { 
        if (groupPrincipal != null) 
        { 
         //get the user 
         using (UserPrincipal userPrincipal = 
        UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName)) 
         { 
          if (userPrincipal != null) 
          { 
           returnValue = userPrincipal.IsMemberOf(groupPrincipal); 
          } 
         } 
        } 
       } 

     } 
関連する問題