0

我想做一个关于从资源中运行 EXE 文件的实验。

Assembly a = Assembly.Load(hm_1.Properties.Resources.HashMyFiles);
MethodInfo method = a.EntryPoint;
if (method != null)
{
     method.Invoke(a.CreateInstance("a"), null);
}

** 对于这个实验,我使用了一个名为 HashMyFiles.exe 的文件,该文件位于我的资源中。

但是,当我调试我的代码时,我得到了错误:

ex {“无法加载文件或程序集'从 hm_1 加载的 59088 字节,版本 = 1.0.0.0,文化 = 中性,PublicKeyToken = null'或其依赖项之一。试图加载格式不正确的程序。” } System.Exception {System.BadImageFormatException}

我阅读了有关在 x64 平台模式下运行 x86 的某些帖子,反之亦然,在视觉工作室中对其进行了更改,但仍然出现相同的错误。

有人有想法吗?注意:我不想在本地创建文件,只想从资源中运行它。

4

1 回答 1

0

您的代码仅适用于托管应用。从资源运行托管应用程序的正确方法:

// You must change 'Properties.Resources.TestCs' to your resources path
// You needed to use 'Invoke' method with 'null' arguments, because the entry point is always static and there is no need to instantiate the class.
Assembly.Load(Properties.Resources.TestCs).EntryPoint.Invoke(null, null);

但是,如果您在资源中有一个非托管应用程序,则无法将其作为程序集加载。您应该将其作为“.exe”文件保存到临时文件夹并作为新进程运行。此代码适用于所有类型的应用程序(托管和非托管)。

// Generate path to temporary system directory.
var tempPath = Path.Combine(Path.GetTempPath(), "testcpp.exe");

// Write temporary file using resource content.
File.WriteAllBytes(tempPath, Properties.Resources.TestCpp);

// Create new process info
var info = new ProcessStartInfo(tempPath);

// If you need to run app in current console context you should use 'false'.
// If you need to run app in new window instance - use 'true'
info.UseShellExecute = false;

// Start new system process
var proccess = Process.Start(info);

// Block current thread and wait to end of running process if needed
proccess.WaitForExit();
于 2017-03-13T07:48:12.100 回答