如何查询gac的汇编文件

问题描述 投票:0回答:1

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

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# .net reflection .net-assembly
1个回答
0
投票

修改这一行:

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

foreach (String f in Directory.GetFiles(myDir, "*.dll", SearchOption.AllDirectories)
© www.soinside.com 2019 - 2024. All rights reserved.