- .Net Core 3.0
- Microsoft.CodeAnalysis.CSharp 3.5.0
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
StringBuilder code = new StringBuilder();
code.AppendLine("namespace DotNetCoreTest");
code.AppendLine("{");
code.AppendLine(" public class TestCode");
code.AppendLine(" {");
code.AppendLine(" public int test(int a)");
code.AppendLine(" {");
code.AppendLine(" a++;");
code.AppendLine(" return a;");
code.AppendLine(" }");
code.AppendLine(" }");
code.AppendLine("}");
string sysFile = typeof(Enumerable).Assembly.Location;
string sysDir = Directory.GetParent(sysFile).FullName;
List<MetadataReference> references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.dll")));
references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.Xml.dll")));
string assemblyName = "DotNetCoreTest";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code.ToString());
CSharpCompilation compilation = CSharpCompilation.Create(assemblyName);
compilation.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
compilation.AddReferences(references);
compilation.AddSyntaxTrees(tree);
string targetPath = "D:\\test.dll";
EmitResult compilationResult = compilation.Emit(targetPath);
string err = "";
if (!compilationResult.Success)
{
foreach (Diagnostic item in compilationResult.Diagnostics)
{
err += "\r\nid: " + item.Id + "\r\nerror: " + item.GetMessage() + "\r\nlocation: " + item.Location.GetLineSpan().ToString();
}
}
id: CS8021 error: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. location: : (0,0)-(0,0) id: CS5001 error: Program does not contain a static 'Main' method suitable for an entry point location: : (0,0)-(0,0)
I repeated the test many times, and the same error message appears. Is there something wrong with my code? Can anyone help me? Thank you