Load assembly from memory

♀尐吖头ヾ 提交于 2020-01-14 13:42:10

问题


I am porting a Java application where classes are loaded and "executed" at runtime from memory (a byte array). I am trying to achieve the same thing in C#, but I am having problems (System.IO.FileNotFoundException exceptions) when trying to load assemblies from byte arrays (using the AppDomain.Load method).

static void Main(string[] args)
{
    var domain = AppDomain.CreateDomain("foo");

    domain.AssemblyResolve += new ResolveEventHandler(domain_AssemblyResolve);

    var assembly = domain.Load("MyAssembly");
}
static Assembly  domain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    // ...
    return Assembly.ReflectionOnlyLoad(File.ReadAllBytes(@"C:\MyAssembly.exe"));
}

Is there a way to load them without the need to persist this byte array into the file system?

Simplifying the idea, we want to have the ability to execute and change (update) code dynamically. We use separate application domains to "load/unload" assemblies.


回答1:


I've just tried this code:

static void Main(string[] args)
        {

            var h = File.ReadAllBytes(@"C:\MyAssembly.exe");

            var g = Assembly.Load(h);            
        }

and it worked fine - I did not get any exceptions. Are you 100% sure that the target assembly exists?




回答2:


Does it have any dependencies? If so, you should load them first.



来源:https://stackoverflow.com/questions/3158217/load-assembly-from-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!