I'm currently working on a program that uses the CSharpCodeProvider to generate an executable. And I need to add a reference to a COM-Lib ("Windows Script Host Model" (wshom.ocx)). This file is located in the sysWOW64-Path. Every time I try to compile the file, it gives me that error:
"Metadata file 'c:\Windows\SysWOW64\wshom.ocx' could not be opened -- 'An attempt was made to load a program with an incorrect format."
The problem is not a platform-problem: The error appears no matter what I set as platform. I tried to set the /platform:x86 parameter; I tried to change the "Builder"'s platform to x86, but it didn't solve the problem.
Here's the code I'm using to compile:
CSharpCodeProvider provider = new CSharpCodeProvider(d);
ICodeCompiler icc = provider.CreateCompiler();
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = false;
parameters.OutputAssembly = destinationDialog.FileName;
parameters.GenerateExecutable = true;
parameters.TreatWarningsAsErrors = false;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Management.dll");
parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
parameters.ReferencedAssemblies.Add("System.XML.dll");
parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
parameters.ReferencedAssemblies.Add(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\System.Speech.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
parameters.ReferencedAssemblies.Add(GetSystemDirectory() + "\\wshom.ocx");
parameters.CompilerOptions = "/unsafe /target:winexe /platform:x86";
CompilerResults results = icc.CompileAssemblyFromSource(parameters, uss);
I hope someone can help me out here...
When add a COM reference in C# project, VS actually create an interop assembly which runtime metadata for the types defined within the original COM library, so for your case, you should create an interop assembly for the washom.ocx, and the refer that assembly.
As how to generate an interop assembly, you can use tlbimp.exe