C#从字节运行

xZe*_*rox 2 .net c# reflection byte assemblies

我正在努力让我的客户端通过下载字节并使用反射打开它来打开另一个程序.我目前在C#控制台应用程序上工作,但是当我尝试在Windows窗体应用程序上执行此操作时,我收到此错误.

"调用的目标引发了异常."

这是代码

using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem.ToString() != null)
        {
            if (MessageBox.Show("Run " + listBox1.SelectedItem.ToString() + "?", "Run this program?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                byte[] bytes;
                using (WebClient client = new WebClient())
                {
                    bytes = client.DownloadData(new Uri("http://example.net/program.exe"));
                }
                RunFromBytes(bytes);
            }
        }
    }
    private static void RunFromBytes(byte[] bytes)
    {
        Assembly exeAssembly = Assembly.Load(bytes);
        exeAssembly.EntryPoint.Invoke(null, null);
    }
Run Code Online (Sandbox Code Playgroud)

Hom*_*mam 5

您必须执行以下操作:

  1. 创建一个新的应用程序域
  2. 将字节数组写入文件
  3. 执行它 ExecuteAssembly

这是代码:

File.WriteAllBytes("yourApplication.exe", bytes);
AppDomain newDomain= AppDomain.CreateDomain("newDomain");
newDomain.ExecuteAssembly("file.exe");
Run Code Online (Sandbox Code Playgroud)

祝好运!