Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Cannot compile simple dynamic code after migration on .netstandard 2.0 (CodeDom throws System.PlatformNotSupportedException)

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{ 
");
sb.Append($"public class {className} {{
");
sb.Append($"public object RunSnippetCode()
{{
");
sb.Append("
return null;
");
sb.Append("
}
");
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(IEnumerable1 referencedAssemblies, IEnumerable1 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same problem with .NetCore 2, but with a bigger CodeDOM project. My solution I am right now building is generating the source from CodeDom and then passing it to Roslyn. (As Roslyn was mentioned in a comment, but only a .NET Framwork solution was posted)

Here is a good example how to use Roslyn - just add the

Microsoft.CodeAnalysis.CSharp NuGet package and System.Runtime.Loader NuGet package

and then use the code here (Or just follow the example): https://github.com/joelmartinez/dotnet-core-roslyn-sample/blob/master/Program.cs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...