Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to compile a string using CodeDom.

Dictionary<string, string> providerOptions = new Dictionary<string, string>
                {"CompilerVersion", "v3.5"}
        CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
        CompilerParameters compilerParams = new CompilerParameters
            GenerateInMemory = true,
            GenerateExecutable = false
        compilerParams.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);

My problem is: In my compiled code I need to use classes from the project I am creating the code in. So I tried to add my current assembly as a reference, however it gives me the following error:

Metadata file 'Path\to\my\executable\MyProject.exe' could not be opened -- 'An attempt was made to load a program with an incorrect format.'

Anybody knows where my mistake is?

Crystal ball says that you built your program targeting .NET 4.0 or higher. So not only can the v3.5 compiler not read the metadata, the final program cannot run either. Specifying the compiler version is just not useful since it always must match your exe settings anyway. – Hans Passant Jul 24, 2016 at 14:53

I had the same need and I solved this way:

compilerParams.ReferencedAssemblies.AddRange(Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(a => a.Name + ".dll").ToArray());

the +".dll" worked with me. if you need to get the full path to the Assembly file you need to load them into a new AppDomain and then get the .Location of each one of them.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.