I am using .NET reflection in order to inspect the content of an assembly. Unfortunately this is not that simple when it comes to inspecting types which are referenced by my assembly but are defined elsewhere.
So, say I have two Assembly
:
Assembly assembly1 = Assembly.LoadFrom("MyAssembly.dll");
Assembly assembly2 = Assembly.LoadFrom("MyReferencedAssembly.dll");
In assembly1
there are types defined in assembly2
so what I want is basically loading assembly2
into assembly1
.
How to achieve this programmatically?
Trying using AppDomain.Load
As suggested in comments, I am trying this:
private Assembly GetAssembly()
{
string[] referencedAssemblyPaths = new[] { "MyReferencedAssembly.dll" };
var domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = Environment.CurrentDirectory;
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
var domain = AppDomain.CreateDomain("AssemblyContextDomain", adevidence, domaininfo);
Assembly assembly = domain.Load(LoadFile("MyAssembly.dll"));
foreach (var path in referencedAssemblyPaths)
{
domain.Load(LoadFile(path));
}
return assembly;
}
private static byte[] LoadFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open);
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return buffer;
}
However I get a problem when invoking domain.Load(LoadFile("MyAssembly.dll"))
as I get FileNotFoundException
:
Could not load file or assembly 'MyAssembly, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Debugging info By debugging I could see that the file exists in the correct place, LoadFile
successfully returns the stream. The problem is in AppDomain.Load
which throws that exception.
- Why is it reporting it cannot find the file?
- Is it trying to load the deendencies and those are the files it cannot find? But I will load dependencies right after...
How the hell am I supposed to load an assembly and its deps?