We are using the following code to create what we thought would be a standalone, .NET Core self-contained console application using CSharpCompilation. A cut down part of the code looks like this:
// Compile the source code.
var csharpParseOptions = new CSharpParseOptions(LanguageVersion.Latest)
.WithPreprocessorSymbols(new[] { "TRACE", "DEBUG" })
.WithKind(SourceCodeKind.Regular);
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);
var csharpCompilation = CSharpCompilation.Create(moduleName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: options);
var result = csharpCompilation.Emit(fileNameOnDisk, Path.Combine(Path.GetDirectoryName(fileNameOnDisk), Path.GetFileNameWithoutExtension(fileNameOnDisk)) + ".pdb");
File.WriteAllText(Path.Combine(Path.GetDirectoryName(fileNameOnDisk), $"{moduleName}.runtimeconfig.json"), "{\r\n \"runtimeOptions\": {\r\n \"tfm\": \"net6.0\",\r\n \"framework\": {\r\n \"name\": \"Microsoft.NETCore.App\",\r\n \"version\": \"6.0.0\"\r\n }\r\n }\r\n}");
The error we get at runtime is:
Unhandled 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.
The resulting exe is pretty small (35K). If we take the same code and paste it into a Visual Studio Console project and build it the resulting exe is around 145K so it looks as though the OutputKind isn't producing a self-contained console exe but one which has to be run with dotnet console.exe. We would like to know how to create a fully self-contained executable.
Thanks!