C#如何从进程中检索代码然后运行它?

Gue*_*ume 5 c# windows exe bytearray process

由于进程是计算机程序的一个实例并包含程序代码及其当前活动,因此我尝试了以下操作:

  • 解析我的进程并检索一个字节数组.
  • 执行这些字节.

我的问题是我检索程序代码及其当前活动,而我只对第一部分感兴趣.

这是我如何检索我的进程"foo"的字节:

 public static byte[] retrieveProcessBytes(String processName) {
        Process process = ApplicationFinder.FromProcessName(processName).First();
        var sharp = new MemorySharp(process);

        List<byte> bytes = new List<byte>();
        IntPtr ptr = IntPtr.Zero;
        try
        {
            while (true) {
                bytes.Add(sharp.Read<byte>(ptr, 1)[0]);
                ptr = IntPtr.Add(ptr, 1);
            }
        }
        catch (Exception e) {
            Console.Write("Exception caught : " + e);
        }
        return bytes.ToArray();
    }
Run Code Online (Sandbox Code Playgroud)

以下是我尝试执行它的方法:

byte[] bytes = retrieveProcessBytes("foo");
Assembly asm = Assembly.Load(bytes);
Object[] Args = new Object[0];
asm.EntryPoint.Invoke(null, Args);
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误:

mscorlib.dll中发生了未处理的"System.BadImageFormatException"类型异常

同时,如果我从"foo.exe"程序中检索字节并执行它们,如下所示,它可以工作.

Byte[] bytes = File.ReadAllBytes(pathToFooExe);
Assembly asm = Assembly.Load(bytes);
Run Code Online (Sandbox Code Playgroud)

我从我的进程中检索的字节数组远远大于我从"foo.exe"文件中检索的字节数组.因为我想我也检索当前的流程活动.

如何只检索进程的代码部分?

它是从IntPtr.Zero开始还是以后开始?我什么时候停止?

任何帮助将不胜感激,提前致谢.