从内存加载程序集

发布于 2024-09-07 15:24:55 字数 692 浏览 1 评论 0原文

我正在移植一个 Java 应用程序,其中类在运行时从内存(字节数组)加载并“执行”。我试图在 C# 中实现同样的目标,但在尝试从字节数组加载程序集(使用 AppDomain.Load )时遇到问题(System.IO.FileNotFoundException 异常)代码>方法)。

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"));
}

有没有办法加载它们而不需要将此字节数组保存到文件系统中?

简化一下想法,我们希望具有动态执行和更改(更新)代码的能力。我们使用单独的应用程序域来“加载/卸载”程序集。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情话难免假 2024-09-14 15:24:55

我刚刚尝试过这段代码:

static void Main(string[] args)
        {

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

            var g = Assembly.Load(h);            
        }

它运行良好 - 我没有遇到任何异常。您是否 100% 确定目标程序集存在?

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?

酒废 2024-09-14 15:24:55

它有任何依赖关系吗?如果是这样,您应该首先加载它们。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文