係 Domain Controller 上以 User Account 是否存在於某 AD Group 方法

 
係 Domain Controller 上以 User Account 是否存在於某 AD Group 方法
 

 
   using System;
   using System.DirectoryServices;
 
   public bool CheckIfUserinGroup(string userName, string userPasswd, string groupName)
   {
      string LDAPstring = "LDAP://vmser001:389/OU=Workstations, DC=deisler, DC=com";
      string domainusername = userName;
      string domainpassword = userPasswd;
 
      string path = "";
 
      if (userName.IndexOf('\\') > 0)
      userName = userName.Split('\\')[1];
 
      DirectoryEntry entry = new DirectoryEntry(LDAPstring, domainusername, domainpassword, AuthenticationTypes.None);
      try
      {
         DirectorySearcher search = new DirectorySearcher(entry);
 
         search.Filter = "(SAMAccountName=" + userName + ")";
         search.PropertiesToLoad.Add("cn");
         SearchResult result = search.FindOne();
 
         if (null == result)
         {
            return false;
         }
 
         path = result.Path;
 
      }
      catch (Exception ex)
      {
         return false;
      }
 
      DirectoryEntry entry1 = new DirectoryEntry(path);
      DirectorySearcher search1 = new DirectorySearcher(entry1);
 
      search1.PropertiesToLoad.Add("memberOf");
 
      try
      {
         SearchResultCollection src = search1.FindAll();
 
         foreach (SearchResult sr in src)
         {
            PropertyValueCollection pvc = sr.GetDirectoryEntry().Properties["memberOf"];
            object[] values = (object[])pvc.Value;
 
            foreach (object value in values)
            {
               if (value.ToString().ToLower().Contains(groupName.ToLower()))
               return true;
            }
         }
      }
      catch (Exception ex)
      {
         return false;
      }
      return false;
   }