0

I'm trying to dynamically generate an executable with the CSharpCodeProvider whose only purpose is to invoke one single method from a specific dll. When I execute the generated file I get a BadImageFormatException.

I already set the platform to x86. When I manually write the code which invokes the method and debug it in Visual Studio, it works perfectly fine.

This is the code for the executable:

using DLLName;

namespace ExampleNamespace
{
    class Program
    {
        public static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            obj.MyMethod();
        }
    }
}

Before dynamically compiling the code I add the assembly via

compilerParameters.ReferencedAssemblies.Add("PathToDLL");

I write the executable to the same directory as the dll.

EDIT

This is the code that I use to invoke the compiler:

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();

parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = @"DirectoryOfDLL\MyMethod.exe";
parameters.ReferencedAssemblies.Add("PathToDLL");

provider.CompileAssemblyFromSource(parameters, code);
svick
  • 236,525
  • 50
  • 385
  • 514
TheRealPetron
  • 31
  • 2
  • 6
  • 2
    "I already set the platform to x86" did you do this with options="/platform:x86" ? If so you will need to provide the code you use to compile. – Alex K. Feb 13 '15 at 13:01
  • Please add the code that actually invokes the compiler. In all likelihood you still have a bitness mismatch (like the generated executable being "any platform" and running on an x64 system, while your DLL is x86). – Jeroen Mostert Feb 13 '15 at 13:01
  • Are you sure you need to specify a bitness? Will 'Any' not suffice? – Laurence Adams Feb 13 '15 at 13:03
  • 1
    @LaurenceAdams: the OP is generating an executable that references a DLL. If the DLL is x86 and the platform you're running on is x64, the executable will also have to be specified as x86, not "Any" (which will default to x64). Of course, for interoperability, the DLL really should have platform "Any" (and then the bitness of your executable doesn't matter). – Jeroen Mostert Feb 13 '15 at 13:27
  • @Jerown Mostert: I fully understand the difference between x86, x64, and Any as well as the meaning of a BadImageFormatException. The OP seems to randomly state that he/she set the platform to x86. It's completely valid to ask the OP if this step was necessary as they are trying to solve a BadImageFormatException. – Laurence Adams Feb 13 '15 at 13:31

0 Answers0