首页 > 解决方案 > 如何在 gac 中查询程序集文件

问题描述

我正在尝试了解有关反射的更多信息,并采用了一些已经构建并添加到其中的代码。现在我正在尝试向 GAC 查询其他程序集和构建类型实例等。我修改了在这里找到的代码,但 myAssemblyList 是空的。你能告诉我我做错了什么吗?我调试并在“var currentAssembly = value.GetAssembly(f);”处放置了一个中断 它返回空值。我看到的所有代码都从当前 AppDomain 填充程序集,但我看到了像 LoadFrom() 这样的方法,它应该与目录路径一起使用。我也看到了这个帖子,整理了一下。

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 文件的目录会导致异常。

标签: c#.netreflection.net-assembly

解决方案


修改这一行:

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

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

推荐阅读