Emit C# Console Application .NET 6.0 throw exception "Could not load file or assembly 'System.Private.CoreLib"

63 Views Asked by At

I try to use the following code to generate a Console Exe Application. The GeneratedExecutable.exe file is created, but when I run the file, I have the following error message :

"Could not load file or assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"

Here the code to Emit the console Exe application :

  static void Main(string[] args)
  {
      string code = @"
      using System;
      class Program
      {
          static void Main()
          {
              Console.WriteLine(""Hello, World!"");
          }
      }";

      string outputPath = Path.Combine(Path.GetTempPath(), "GeneratedExecutable.exe");

      GenerateExecutable(code, outputPath);
  }

  private static void GenerateExecutable(string code, string outputPath)
  {
      var stringText = SourceText.From(code, Encoding.UTF8);
      var parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(stringText, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10), outputPath);
      var metaDataReference = new List<MetadataReference>();

      metaDataReference.Add(MetadataReference.CreateFromFile(typeof(Object).Assembly.Location));
      metaDataReference.Add(MetadataReference.CreateFromFile(typeof(Console).Assembly.Location));
      var s = MetadataReference.CreateFromFile(Assembly.Load(Assembly.GetEntryAssembly().GetReferencedAssemblies().Single(a => a.Name == "System.Runtime") ).Location);
      metaDataReference.Add(s);

      var defaultCompilationOptions =
      new CSharpCompilationOptions(OutputKind.ConsoleApplication)
              .WithUsings(new string[] { "System" });

      var compilation = CSharpCompilation.Create(Path.GetFileName(outputPath), new SyntaxTree[] { parsedSyntaxTree }, metaDataReference, defaultCompilationOptions);
      var result = compilation.Emit(outputPath);

      Console.WriteLine("Compilation OK : "+result.Success.ToString());
  }
0

There are 0 best solutions below