C# - Assembly.Load - Exception thrown: 'System.BadImageFormatException' in mscorlib.dll

785 views Asked by At

I would like to make an experiment about running an EXE file from Resources.

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

** For this experiment I used a file named HashMyFiles.exe which is in my resources.

However, when I debug my code I get the error:

ex {"Could not load file or assembly '59088 bytes loaded from hm_1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format."} System.Exception {System.BadImageFormatException}

I read certain posts about running x86 on x64 platform mode and viceversa, changes it in visual studios, and still the same error.

Does anyone have an idea? Note: I do not want to create the file locally, only to run it from the resource.

1

There are 1 answers

1
Ivan Kishchenko On

Your code only works for managed apps. The correct way to run managed application from resources:

// 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);

But if you have an unmanaged app in resources, you can`t load it as an assembly. You should save it as '.exe' file to temporary folder and run as a new process. This code works fine for all types of applications (managed and unmanaged).

// 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();