0
  1. .Net Core 3.0
  2. 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

2
  • I tried to run a test with your code here dotnetfiddle.net/mKYCTJ and I think there are some other troubles other than the empty void Main Commented Jul 1, 2020 at 9:20
  • The same code, dynamic compilation under the .net framework is completely okay. Commented Jul 1, 2020 at 10:31

1 Answer 1

1

Thank you for everybody. This question has been solved, next share the solution, but you must add a dependence 'Microsoft CodeAnalysis CSharp'

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public class CodeCompiler
{

    Assembly TranslateCode(string code, ref string err)
    {
        Assembly asse = null;

        Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
        List<MetadataReference> metadataReferences = new List<MetadataReference>();
        PortableExecutableReference portable = null;
        int len = asses.Length;
        int num = 0;
        Assembly item = null;
        while (num < len)
        {
            try
            {
                item = asses[num];
                if (string.IsNullOrEmpty(item.Location)) continue;
                portable = MetadataReference.CreateFromFile(item.Location);
                metadataReferences.Add(portable);
            }
            catch (Exception)
            {

                //throw;
            }
            finally
            {
                num++;
            }
        }
            
        var references1 = metadataReferences.ToArray(); 

        string assemblyName = Path.GetRandomFileName();

        SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
            
        CSharpCompilation compilation = CSharpCompilation.Create(
            assemblyName,
            syntaxTrees: new[] { syntaxTree },
            references: references1, 
            options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

        using (var ms = new MemoryStream())
        {
            EmitResult result = compilation.Emit(ms);

            if (!result.Success)
            {
                IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                    diagnostic.IsWarningAsError ||
                    diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    //Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    err += string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage())+"\r\n";
                }
            }
            else
            {
                // The assembly is loaded from memory when the compilation is successful
                ms.Seek(0, SeekOrigin.Begin);
                asse = Assembly.Load(ms.ToArray());
            }
        }

        return asse;
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.