如何查询 gac 的程序集文件

how to query gac for assembly files

我正在努力学习更多关于反射的知识,并使用了一些已经构建并添加到其中的代码。现在我正在尝试在 GAC 中查询其他程序集和构建类型实例等。我修改了我找到的代码 here, but myAssemblyList is empty. Can you tell me what I am doing wrong? I debugged and placed a break at "var currentAssembly = value.GetAssembly(f);" and it returns null. All the code I have seen populates Assemblies from the current AppDomain, but I have seen methods like LoadFrom(), which should work with a directory path. I also saw this post,并编译了它。

class Program
{
    static void Main(string[] args)
    {
        AppDomainSetup domaininfo = new AppDomainSetup();
        domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);
        Type type = typeof(Proxy);
        var value = (Proxy)domain.CreateInstanceAndUnwrap(
            type.Assembly.FullName,
            type.FullName);
        //String myDir = "C:\Windows\Microsoft.NET\assembly\GAC_64\";
        String myDir = "C:\Windows\Microsoft.NET\assembly\";
        List<Assembly> myAssemblyList = new List<Assembly>();
        foreach (String f in Directory.GetFiles(myDir, "*.dll", SearchOption.AllDirectories))
        {
            //Console.WriteLine($"Here is f: {f}");
                var currentAssembly = value.GetAssembly(f);
                if (currentAssembly != null)
                {
                    myAssemblyList.Add(currentAssembly);
                    Console.WriteLine(currentAssembly.FullName);
                    //Console.ReadLine();
                }
            Console.WriteLine($"Total Assemblies found: {myAssemblyList.Count}");
        }
        Console.WriteLine($"Total Assemblies found: {myAssemblyList.Count}");
        Console.ReadLine();
    }
}
public class Proxy : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            return Assembly.LoadFile(assemblyPath);
        }
        catch (Exception)
        {
            return null;
            // throw new InvalidOperationException(ex);
        }
    }
}

我跳回一个目录,并尝试从 GAC_* 收集,即 32、64 和 MSIL。我为 currentAssembly 添加了 null 测试以解决 GetAssembly() 的问题。但是仍然有一些包含dll和非dll文件的目录会导致异常。

修改这一行:

foreach (String f in Directory.GetFiles(myDir))

foreach (String f in Directory.GetFiles(myDir, "*.dll", SearchOption.AllDirectories)