Farhad Alizadeh Noori February 2016

Programmatically compiling source code using Roslyn

So I've been trying to compile a piece of code programmatically with Roslyn. For some reasons the references that I add just don't end up in the Compilation class. So when I look at the referenced assembly after I use 'AddReferences', the list is empty. Hence, when I try to emit, I get "Object" not defined in the diagnostics. Can anyone point me to the problem?

Microsoft.CodeAnalysis.SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
public static class Program
{
    public static void Main()
    {
        System.Console.WriteLine(""Hello"");            
    }
}
");
    string autoreferences = @"mscorlib.dll,System.Core.dll";
    List<string> usings = new List<string>();
    string netAssembliesDirectory = Path.GetDirectoryName(typeof(object).Assembly.Location);
    var refs = new List<string>();
    foreach (string reference in autoreferences.Split(','))
        refs.Add(netAssembliesDirectory + "\\" + reference);


    CSharpCompilation compilation = CSharpCompilation.Create("ConsoleTest")
        .WithOptions(
            new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("System"))
        .AddSyntaxTrees(syntaxTree);
    compilation.AddReferences(refs.Where(r => r != "").Select(r => MetadataReference.CreateFromFile(r)));
    var er = compilation.Emit(@"C:\" + "ConsoleTest");

Answers


SLaks February 2016

Roslyn objects are immutable.

compilation.AddReferences() returns a new compilation instance with those references.
You're ignoring that new instance.

You need to call Emit() on the compilation instance that has your references.

Post Status

Asked in February 2016
Viewed 2,835 times
Voted 7
Answered 1 times

Search




Leave an answer