2010-07-23 29 views
1

從Windows服務中檢索用戶所屬組的列表的最佳方式是什麼?從Windows服務獲取用戶所屬組的列表

List<string> groups = new List<string>(); 

foreach (IdentityReference ir in new WindowsIdentity(name).Groups) 
{ 
    SecurityIdentifier sid = new SecurityIdentifier(ir.Value); 
    NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount)); 
    groups.Add(ntAccount.ToString()); 
} 

我試圖使用上面的代碼,但它引發了以下錯誤。

Error communicating with client: System.Security.SecurityException: Incorrect function. 

回答

0

下面是我最後使用的代碼。我不知道LDAP,但它似乎可能引起一些安全問題...

public static List<string> GetUserGroups(string name) 
    { 
     List<string> groups = new List<string>(); 
     DirectorySearcher search = new DirectorySearcher(""); 
     int groupCount; 
     int counter; 
     string GroupName; 
     string DataToWriteGroups; 

     search.Filter = "(&(objectClass=user)(SAMAccountName=" + name + "))"; 
     search.PropertiesToLoad.Add("memberOf"); 


     SearchResult result = search.FindOne(); 


     groupCount = result.Properties["memberOf"].Count; 

     if (groupCount > 0) 
     { 
      DataToWriteGroups = "Group(s) Belongs To User - " + name + ""; 
      for (counter = 0; counter <= groupCount - 1; counter++) 
      { 
       GroupName = ""; 
       GroupName = (result.Properties["memberOf"][counter].ToString()); 
       groups.Add(GroupName); 
      } 
     } 

     return groups; 
    } 
相關問題