执行Byte数组作为新程序

时间:2012-05-17 20:59:10

标签: c# bytearray

我正在创建一个程序,看看我是否可以在C#中运行一个字节数组。

程序应该获取一个字节数组“MyBinaryData”并加载+运行它作为一个新程序。 将有一个文本框,您可以在其中输入字节以查看结果(这是一个实验;))。 我试过这个:

 byte[] binaryData = System.IO.File.ReadAllBytes("MyBytes.txt");  // the bytes are in a .txt file for simple tests before becoming a textbox.
 Assembly LoadByte = Assembly.Load(binaryData);
        MethodInfo M = LoadByte.EntryPoint;

        if (M != null)
        {                object o = LoadByte.CreateInstance(M.Name);
            M.Invoke(o, new Object[] { null });  // this gives the error
        } 
        else {  
         ..... fail code here.... 
             } 

问题是它出现了这个错误: “System.Reflection.TargetInvocationException:......必须在应用程序中创建第一个IWin32Window对象之前调用SetCompatibleTextRenderingDefault。”

我的第二个测试是:

 Assembly assembly = Assembly.Load(binaryData);

 Type bytesExe = assembly.GetType(); // problem: the GetType(); needs to know what class to run.
 Object inst = Activator.CreateInstance(bytesExe);

但是这需要知道它需要运行的字节数组中的哪个类。

然后我尝试了:

var bytes = Assembly.Load(binaryData);
var entryPoint = bytes.EntryPoint;
var commandArgs = new string[0];
var returnValue = entryPoint.Invoke(null, new object[] { commandArgs });

但它给了我这个: “System.Reflection.TargetInvocationException:调用目标抛出了异常.---> System.InvalidOperationException:必须在应用程序中创建第一个IWin32Window对象之前调用SetCompatibleTextRenderingDefault。”

我的program.cs是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Crypter
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form2());
    }
}

}

我可以通过其他方式打开整个程序吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

你有两种方式

第一种方法从该字节数组中生成.exe然后启动它

第二次看这个execute byte array