从内存运行exe
以下是从内存加载运行exe的方法
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;