DirectoryEntry 不返回 .NET 中的组成员,但在 ASP.NET 中有效

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

我正在尝试构建一个列表,其中包含计算机上的所有本地组以及每个组中的所有用户。

这是我正在使用的代码

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)
    { }
}

这在 ASP.NET IIS 8.1 服务器上工作得很好。

我正在尝试使用 Visual Studio 2017、.NET 4.6.1 使用 C# 将其转换为命令行可执行文件,但它无法编译,甚至在编译后也找不到该组成员。

  1. 当我将相同的代码粘贴到 Visual Studio C# 项目时,出现 foreach (object userG in (IEnumerable)computerGroupEntry.Invoke("Members")) 错误 带有错误消息

    Error CS1579 foreach statement cannot operate on variables of type 'IEnumerable' because 'IEnumerable' does not contain a public instance definition for 'GetEnumerator'

  2. 如果我将行更改为 foreach (object userG in computerGroupEntry.Properties["Members"]) 它会编译,但在 运行 时它找不到任何 属性 `Members

那么,为什么代码在 ASP.NET 上运行,但 C# 可执行文件没有看到组的任何用户 Members(都 运行 在同一台机器上)?

此外,如果有人知道为什么它在 .NET 中使用 IEnumerable 语句时抛出错误,但在 ASP.NET.

中工作

你发布的代码在控制台应用程序(它是一个可执行文件)中按原样为我工作,在 VS 2019 中使用目标 .NET Framework 4.6.1。 请验证以下参考资料是否存在。

using System.Collections;
using System.Collections.Generic;

(IEnumerable)computerGroupEntry.Invoke("Members") 需要 System.Collections

我提供了组 "Administrators",我能够检索到 "wsAdmin"、"Domain Admins"