我试图学习有关反射的更多信息,并采用了一些已构建并添加到其中的代码。现在,我正在尝试向GAC查询其他程序集和构建类型实例等。我修改了发现的here代码,但myAssemblyList为空。你能告诉我我做错了什么吗?我进行了调试,并在“ var currentAssembly = value.GetAssembly(f);”处停了下来。它返回null。我看到的所有代码都从当前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文件的目录会导致异常。
答案 0 :(得分:0)
修改此行:
foreach (String f in Directory.GetFiles(myDir))
与
foreach (String f in Directory.GetFiles(myDir, "*.dll", SearchOption.AllDirectories)