Reference issue while compiling code inside a .net core 2.0 app.

  • Thread starter Thread starter Magnus, Sweden
  • Start date Start date
M

Magnus, Sweden

Guest
Hello,

I'm really stuck on this issue, what reference should I add to make it work? I'm almost on the way to give up on porting to core.

It just claim that there is no console class. This was never a issue to figure out in .net framework 4.


Regards,
Magnus

Error message is : (9,21): error CS0103: The name 'Console' does not exist in the current context


using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace CoreTest
{
class Program
{
public static void Message()
{
Console.WriteLine("This works!");
}

static void Main(string[] args)
{

Message();

string theCode = @"

using System;

public static class Code
{
public static void Message()
{
Console.WriteLine(""This dont work!"");
}
}

";

var references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location));
// references.Add(MetadataReference.CreateFromFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5\System.Console.dll"));
// references.Add(MetadataReference.CreateFromFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5\System.Net.dll"));
// references.Add(MetadataReference.CreateFromFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5\System.dll"));
// references.Add(MetadataReference.CreateFromFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5\System.Reflection.dll"));
// references.Add(MetadataReference.CreateFromFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5\System.Collections.dll"));
// references.Add(MetadataReference.CreateFromFile(@"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5\System.IO.dll"));

var compilation = CSharpCompilation.Create("ExternalDLL")
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(references)
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(theCode));

var emitResult = compilation.Emit("external.dll");

if (!emitResult.Success)
{
foreach (var diagnostic in emitResult.Diagnostics)
{
Console.WriteLine(diagnostic.ToString());
}
}
else
{
var ExternalDLL = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath("external.dll"));
ExternalDLL.GetType("Code").GetMethod("Message").Invoke(null, null);
}
Console.ReadKey();
}
}
}

Continue reading...
 
Back
Top