【发布时间】:2019-02-13 16:07:03
【问题描述】:
我正在尝试了解有关反射的更多信息,并获取了一些已经构建并添加到其中的代码。现在我正在尝试向 GAC 查询其他程序集和构建类型实例等。我修改了我找到的代码 here,但 myAssemblyList 是空的。你能告诉我我做错了什么吗?我调试并在“var currentAssembly = value.GetAssembly(f);”处放置了一个中断它返回空值。我看到的所有代码都从当前 AppDomain 填充程序集,但我看到了像 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