简体   繁体   中英

DirectoryEntry not returning group members in .NET but works in ASP.NET

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.

  1. When I paste the same code into Visual Studio C# project it gives me error for 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'

  2. If I change the line to foreach (object userG in computerGroupEntry.Properties["Members"]) it compiles but at run time it doesn't find any property `Members

So 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM