'Load .NET Core x64 exe as .NET assembly and start process [duplicate]

I need to convert an executable to Bytes, and then start a process with it.

What im using now is like:

using System.Reflection;
using System.Threading;

public static class MemoryUtils
{
    public static Thread RunFromMemory(byte[] bytes)
    {
        var thread = new Thread(new ThreadStart(() =>
        {
            var assembly = Assembly.Load(bytes);
            MethodInfo method = assembly.EntryPoint;
            if (method != null)
            {
                method.Invoke(null, null);
            }
        }));

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();

        return thread;
    }
}

Implementation:

var bytes = File.ReadAllBytes(@"C:\myexecutable.exe");
MemoryUtils.RunFromMemory(bytes).Join();

But the problem is, it only works with 32bit executables, and the executable is 64bit. Any idea of how I could do it, any suggestions? Thank you

The error I'm getting:

System.BadImageFormatException: 'Bad IL format.'


Solution 1:[1]

But the problem is, it only works with 32bit processes, and the executable is 64bit. Any ideia of how I could do it, any suggestions?

It's not entirely clear what error you're getting, or what you mean by "only works with 32bit processes". However, I suspect that you are trying to load the wrong file.

A non-portable .NET Core .exe is not a valid managed assembly. If you want to be able to load your .NET Core program using Assembly.Load(), you must compile it as a portable assembly, and you must load the .dll file that is generated, not the .exe (the latter just being the little stub that knows how to run the .dll).

So, you need to:

  1. Make sure you are compiling/publishing myexecutable.csproj as a portable assembly, and
  2. Make sure you load myexecutable.dll, and not myexecutable.exe (i.e. var bytes = File.ReadAllBytes(@"C:\myexecutable.dll");)

Please see Build .NET Core console application to output an EXE for lots more details about the various ways you can compile a .NET Core program.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Duniho