How to compile a C# file with Roslyn programmatically?

后端 未结 2 1515
无人及你
无人及你 2020-12-02 13:14

I read that you can\'t compile C# 6.0 with CSharpCodeProvider and therefor trying to do with with Roslyn. But I can\'t find a good example how to load a file and then compil

2条回答
  •  没有蜡笔的小新
    2020-12-02 13:59

    You have to use the NuGet package Microsoft.CodeAnalysis.CSharp.

    var syntaxTree = CSharpSyntaxTree.ParseText(source);
    
    CSharpCompilation compilation = CSharpCompilation.Create(
        "assemblyName",
        new[] { syntaxTree },
        new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) },
        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
    
    using (var dllStream = new MemoryStream())
    using (var pdbStream = new MemoryStream())
    {
        var emitResult = compilation.Emit(dllStream, pdbStream);
        if (!emitResult.Success)
        {
            // emitResult.Diagnostics
        }
    }
    

提交回复
热议问题