Trying to compile this sample of code:
var c = new CSharpCodeProvider();
var cp = new CompilerParameters();
var className = $"CodeEvaler_{Guid.NewGuid().ToString("N")}";
// doesn't work with or without netstandard reference
var netstandard = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
cp.ReferencedAssemblies.Add(netstandard.Location);
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
var sb = new StringBuilder("");
sb.Append("namespace Jobs.Dynamic{ \n");
sb.Append($"public class {className} {{\n");
sb.Append($"public object RunSnippetCode()\n{{\n");
sb.Append("\nreturn null;\n");
sb.Append("\n}\n");
sb.Append("}");
sb.Append("}");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
Everything was ok before migration on .netstandard 2.0
A simple class has to be generated and it works if just copy the code and run it in Visual Studio. The class with one method that returns null. Now CompileAssemblyFromSource method 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) at CnetContent.Jobs.DynamicCode..ctor(IEnumerable
1 referencedAssemblies, IEnumerable
1 usings, String methodArgs, String codeSnippet) at CnetContent.Jobs.Core.JobBase.EvalRunCondition(String& error)
I updated System.CodeDom and this library supports .netstandard 2.0, but this code still doesn't work. Could not find any cases with similar problems. Any ideas? Thank you in advance!
In my case I was migrating a project from
.NET Framework 4.7.2
to.NET Standard 2.0
. In this project I have code to generate an assembly during runtime by usingCSharpCodeProvider
. Could compile the project but then during runtime my code threw an exception when generating an assembly from Dom. I got this error:As a consequence the assembly was not created during runtime.
In order to fix that I have added
.netstandard
for the compiler as a referenced assembly like that:That did the trick for me.