1

As I wrote in the title I am looking for a way to get all the local groups a certain user belongs too without the username or only a part of it using c#, is there any way to do it?

Already tried using The codes in this post, How to get the groups of a user in Active Directory? (c#, asp.net), non of them worked

        public static List<string> GetAdGroupsForUser2(string userName, string domainName = null)
        {
            var result = new List<string>();

            if (userName.Contains('\\') || userName.Contains('/'))
            {
                domainName = userName.Split(new char[] { '\\', '/' })[0];
                userName = userName.Split(new char[] { '\\', '/' })[1];
            }

            using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName))
            using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName))
            using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name)))
            {
                searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName);
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PropertiesToLoad.Add("cn");

                foreach (SearchResult entry in searcher.FindAll())
                    if (entry.Properties.Contains("cn"))
                        result.Add(entry.Properties["cn"][0].ToString());
            }
            MessageBox.Show("got here"); // message box not showing
            return result;
        }

Any help would be appreciated

Ran Firrer
  • 43
  • 5
  • can you drop a code sample? – Ndubuisi Jr Apr 29 '20 at 08:22
  • What specifically didn't work in the linked solution? Did you not get the user? Did you not get the users groups? – Lars Kristensen Apr 29 '20 at 08:22
  • @LarsKristensen , My program crashed every time i ran it – Ran Firrer Apr 29 '20 at 08:25
  • @RonMirer What was the error message? Perhaps you can edit your question to include the code you are using (remember to blank out any credentials or domain names) – Lars Kristensen Apr 29 '20 at 08:55
  • @LarsKristensen i added the code , idont get an error my program just stops, it shouldnt when i remove the code it works fine – Ran Firrer Apr 29 '20 at 10:57
  • The code sample works for me, with my username and domain - I get the list of groups I am a part of. There's nothing in that piece of code that would terminate a program. Have you tried stepping through the code with debugger? Does your application have a global exception handler? – Lars Kristensen Apr 29 '20 at 13:00
  • @RanFirrer Did you find a solution to this? Or figure out what the problem was? – Lars Kristensen May 07 '20 at 07:37

0 Answers0