We are generating code dynamically to produce a .NET Core console application and then compiling it using:
var csharpParseOptions = new CSharpParseOptions(LanguageVersion.Latest);
csharpParseOptions = csharpParseOptions.WithPreprocessorSymbols(new[] { "TRACE", "DEBUG" });
var syntaxTree = CSharpSyntaxTree.ParseText(code, options: csharpParseOptions);
var compilationUnitSyntax = syntaxTree.GetCompilationUnitRoot();
var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: OptimizationLevel.Debug, platform: Platform.X64)
.WithModuleName("TestConsole")
.WithMetadataImportOptions(MetadataImportOptions.All)
.WithDeterministic(true)
.WithConcurrentBuild(true);
var csharpCompilation = CSharpCompilation.Create(@"TestConsole", syntaxTrees: new[] { syntaxTree }, references: references, options: options);
We can then work without any problems against the generated assembly (in memory) obtained using:
using (var memoryStream = new MemoryStream())
{
var emitResult = csharpCompilation.Emit(memoryStream);
memoryStream.Position = 0;
_assembly = Assembly.Load(memoryStream.ToArray());
}
However, when we write the console.exe to disk using:
csharpCompilation.Emit(fileNameOnDisk, Path.Combine(Path.GetDirectoryName(fileNameOnDisk), Path.GetFileNameWithoutExtension(fileNameOnDisk)) + ".pdb");
and try to run it from there we get the following exception:
System.TypeLoadException: Could not load type 'System.Object' from assembly 'System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' because the parent does not exist.
Copying the same generated code (Program.cs) into an empty Console project works perfectly but we notice that the size of the executable is significantly larger.
Does anyone have any ideas how to go about fixing this problem? Thanks.