I have a simple project with .NetFramework 3.5 Class library
.
I compile and run c# dynamic code
at the runtime
(with CodeDom
) in the .NetFramework
project and call from the Asp.NetCore 2.0
project.
when I call the BuildAssembly
Method in Common
class from Asp.NetCore 2.0
project, I encounter with this Error: (CodeDom throws)
"System.PlatformNotSupportedException":"Operation is not supported on this platform." at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)
following code:
.NetFrameWork 3.5:
public class Common
{
public Assembly BuildAssembly(string code)
{
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters compilerparams = new CompilerParameters();
compilerparams.GenerateExecutable = false;//Generate an executable instead of a class library
compilerparams.GenerateInMemory = false; //Save the assembly as a physical file.
compilerparams.ReferencedAssemblies.Add("mscorlib.dll");
compilerparams.ReferencedAssemblies.Add("System.dll");
compilerparams.ReferencedAssemblies.Add("System.Data.dll");
compilerparams.ReferencedAssemblies.Add("System.Xml.dll");
CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerparams, code);
if (results.Errors.HasErrors)
{
StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
foreach (CompilerError error in results.Errors)
{
errors.AppendFormat("Line {0},{1}\t: {2}\n",
error.Line, error.Column, error.ErrorText);
}
throw new Exception(errors.ToString());
}
else
{
return results.CompiledAssembly;
}
}
}
Asp.NetCore 2.0:
public IActionResult Test()
{
string code = @"
using System;
using System.Text;
using System.Data;
using System.Reflection;
using System.ComponentModel;
namespace testNameSpace
{
public class DynamicClass
{
public string Test() { return ""Hello world""; }
}
}";
var res = new Common().BuildAssembly(code);
return Json("ok");
}
I searched at the web and accoding this Link I install the Microsoft.CodeAnalysis.CSharp
nuget package and tested but It's not working.
I can not compile the simple code from this way.
how to fix this error?