I'm trying to build a list of all the local groups on a machine and all the users in each of those groups.
This is the code I'm using
foreach (string group in groups)
{
try
{
using (DirectoryEntry computerGroupEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1},group", Environment.MachineName, group)))
{
foreach (object userG in (IEnumerable)computerGroupEntry.Invoke("Members"))
{
DirectoryEntry user = new DirectoryEntry(userG);
users.Add(group, user.Properties["Name"].Value.ToString());
}
}
}
catch (Exception)
{ }
}
This works just fine in ASP.NET on an IIS 8.1 server.
I'm trying to convert this into an command line executable file using Visual Studio 2017, .NET 4.6.1 using C# but it won't compile and even after compiling it won't find the group members.
foreach (object userG in (IEnumerable)computerGroupEntry.Invoke("Members"))
with an error message
Error CS1579 foreach statement cannot operate on variables of type 'IEnumerable' because 'IEnumerable' does not contain a public instance definition for 'GetEnumerator'
foreach (object userG in computerGroupEntry.Properties["Members"])
it compiles but at run time it doesn't find any property `MembersSo why is the code working on ASP.NET but the C# executable not seeing any user Members
for the groups (both running on the same machine)?
Also if anyone has an idea why it's throwing an error with the IEnumerable statement in .NET but working in ASP.NET.
The code you posted worked for me as-is in console application(which is an executable) with targeted .NET framework 4.6.1 in VS 2019. Please verify if the below references are present.
using System.Collections;
using System.Collections.Generic;
(IEnumerable)computerGroupEntry.Invoke("Members")
needs System.Collections
I provided the group "Administrators" and I was able to retrieve "wsAdmin", "Domain Admins"