예제 #1
0
        public static List <string> GetGroups(string dominio, string user, string pwd, string path)
        {
            string            username          = dominio + "\\" + user;
            DirectoryEntry    searchRoot        = new DirectoryEntry(path, username, pwd);
            DirectorySearcher directorySearcher = new DirectorySearcher(searchRoot);
            List <string>     listaGrupos       = new List <string>();

            try
            {
                directorySearcher.Filter = "samAccountName=" + user.Trim();
                DirectoryEntry directoryEntry = directorySearcher.FindOne().GetDirectoryEntry();
                directoryEntry.RefreshCache(new string[] { "tokenGroups" });
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("(|");
                foreach (byte[] array in directoryEntry.Properties["tokenGroups"])
                {
                    stringBuilder.Append("(objectSid=");
                    for (int i = 0; i < array.Length; i++)
                    {
                        stringBuilder.AppendFormat("\\{0}", array[i].ToString("X2"));
                    }
                    stringBuilder.AppendFormat(")", Array.Empty <object>());
                }
                stringBuilder.Append(")");
                IEnumerator enumerator = new DirectorySearcher(searchRoot, stringBuilder.ToString()).FindAll().GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        string item = (string)((SearchResult)enumerator.Current).Properties["samAccountName"][0];
                        listaGrupos.Add(item);
                    }
                }
                finally
                {
                    IDisposable disposable = enumerator as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                listaGrupos.Add(ex.Message);
            }
            return(listaGrupos);
        }