从内存运行exe
以下是从内存加载运行exe的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
bt = ReadFileFromEmbeddedResourcesAsByte("Calculator.exe"); bt = ReadFileAsByte("C:\\Calculator.exe"); if (!(bt == null)) { RunExecutableFromMemory(bt); } else { MsgBox("Error"); } private byte[] ReadFileAsByte(string Filepath) { if ((IO.File.Exists(Filepath) == false)) { MsgBox("File not exists"); return null; } FileStream fstream = new FileStream(Filepath, FileMode.Open, FileAccess.Read); BinaryReader binReader = new BinaryReader(fstream); byte[] fbinary = null; try { fbinary = binReader.ReadBytes(Convert.ToInt32(fstream.Length)); fstream.Close(); binReader.Close(); return fbinary; } catch (Exception ex) { MsgBox(ex.Message.ToString); } finally { if (!(fstream == null)) { fstream.Close(); } if (!(binReader == null)) { binReader.Close(); } } return fbinary; } // 从嵌入式资源作为字节码读取可执行文件 byte[] ReadFileFromEmbeddedResourcesAsByte(string fileToGetFromAssembly) { Stream resFilestream; System.Reflection.Assembly Exassembly = this.GetType.Assembly.GetCallingAssembly; string Mynamespace = Exassembly.GetName().Name.ToString(); BinaryReader binReader = null; byte[] fbinary = null; try { resFilestream = Exassembly.GetManifestResourceStream((Mynamespace + ("." + fileToGetFromAssembly))); if (!(resFilestream == null)) { binReader = new BinaryReader(resFilestream); fbinary = binReader.ReadBytes(Convert.ToInt32(resFilestream.Length)); resFilestream.Close(); binReader.Close(); return fbinary; } } catch (Exception ex) { MsgBox(ex.Message.ToString); } finally { if (!(resFilestream == null)) { resFilestream.Close(); } if (!(binReader == null)) { binReader.Close(); } } return fbinary; } // 从内存运行可执行文件 private void RunExecutableFromMemory(byte[] bytes) { try { System.Reflection.Assembly asmb = System.Reflection.Assembly.Load(bytes); MethodInfo entryPt = asmb.EntryPoint; if (!(entryPt == null)) { object objectValue = RuntimeHelpers.GetObjectValue(asmb.CreateInstance(entryPt.Name)); entryPt.Invoke(RuntimeHelpers.GetObjectValue(objectValue), null); } } catch (TargetParameterCountException ex) { } catch (Exception ex) { } } // 嵌入址源字节码 private byte[] bt; // 可执行文件字节码 private byte[] bt; |
如果您对C#游戏开发感兴趣,可以扫下面二维码加入我们的QQ群来一起学习交流
原创文章,转载请注明本文链接地址(违者必究):从内存运行exe