Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading an assembly by Bytes loses the location

I want to load the assembly via the following

var loadedAssembly = Assembly.Load(File.ContentsAsBytes);

the File.ContentAsBytes returns the dll as a byte[], via the following

System.IO.File.ReadAllBytes("dll location");

The issue is the loaded assembly (loadedAssembly) loses its phyisical location

  • loadedAssembly.CodeBase - is set to the assembly which is loading it (which is not correct)
  • loadedAssembly.Location - is empty

Is there a way to load from a byte[] and getting a similar result to Assembly.LoadFile as I need the the result to work with the AppDomain.CurrentDomain.AssemblyResolve

like image 221
dbones Avatar asked May 16 '13 20:05

dbones


People also ask

How does assembly load work?

Loads an assembly given its AssemblyName. The assembly is loaded into the domain of the caller using the supplied evidence. Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.

Which method from assembly class can be used to load an assembly from a byte array?

To load an assembly from a byte array with the trust level of the application domain, use the Load(Byte[], Byte[], SecurityContextSource) method overload.

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.

When assembly will load on AppDomain?

Instantiating ClassIf an assembly is loaded into the same AppDomain, then the class can be instantiated in the usual way. But if an assembly is loaded into a different AppDomain then it can be instantiated using reflection. Another way is an interface.


1 Answers

A byte array byte[] is simply a stream of bytes in memory. It has no correlation to any file at all. That byte array could have been read from file, downloaded from a web server, or created spontaneously by a random number generator. There is no extra data that "goes with it".

If you want to maintain the file location where the byte array was originally read from, then you must maintain that data separately in another variable. There is no way to "attach" the extra data to the byte[] variable.

When you use Assembly.Load to load the byte array as an assembly, it has no way to know where that byte array came from, because that extra data is not provided to the Load function.

As a workaround, is there a way you can save your byte array to a temporary file, use Assembly.LoadFile to give you the data you need and link the Location back to your original byte array?

like image 186
Matt Houser Avatar answered Sep 17 '22 02:09

Matt Houser