Except System.Platformnotsupportedexception when trying to compile code with Codedom

Asked

Viewed 55 times

0

I’m using a code, which I saw in a reply of this page:

var csc = new CSharpCodeProvider();
        var parameters = new CompilerParameters(
                    new[] { "mscorlib.dll", "System.Core.dll" }, "teste.exe", true)
        {
            GenerateExecutable = true
        };
       CompilerResults compiledAssembly = csc.CompileAssemblyFromSource(parameters,
        @"
    using System;
    class Program {
      public static void Main() {
            Console.WriteLine(""Hello world."");
      }
    }");

        var errors = compiledAssembly.Errors
                                     .Cast<CompilerError>()
                                     .ToList();

        if (errors.Any())
        {
            errors.ForEach(Console.WriteLine);
            return;
        }

        Module module = compiledAssembly.CompiledAssembly.GetModules()[0];

        Type mt = null;
        if (module != null)
            mt = module.GetType("Program");

        MethodInfo methInfo = null;
        if (mt != null)
            methInfo = mt.GetMethod("Main");

        if (methInfo != null)
            Console.WriteLine(methInfo.Invoke(null, null));

However when I try to compile I get the following error:

System.PlatformNotSupportedException
  HResult=0x80131539
  Message=Operation is not supported on this platform.
  Source=System.CodeDom
  StackTrace:
   at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
   at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)
   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)
   at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)
   at ConsoleApp7.Program.Main(String[] args) in C:\Users\THIAGO\source\repos\ConsoleApp7\ConsoleApp7\Program.cs:line 18

I’m using these references:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Linq;
using System.Reflection;
  • Some of the classes in this namespace are incomplete, some are just examples. It’s a project. Net Core or Framework?

  • I think . Net Core.

  • is a console application with the first code in main, and the references listed above.

  • Some things are different for . Net Core and . Net Framework because Core is designed to be cross-platform. Have a look at this code: https://laurentkempe.com/2019/02/18/dynamically-compile-and-run-code-using-dotNET-Core-3.0/

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.