How to compile a C# file with Roslyn programmatically?

后端 未结 2 1491
无人及你
无人及你 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:56

    I have created a sample for you to work with. You need to tweak it to use the run time for .Net 4.6 so that CSharp6 version is availble to you. I have added little details so that you can choose the options of compilations.

    Changes required - Change the path of runtime to target .Net 4.6 Change the LanguageVersion.Csharp5 to LanguageVersion.Csharp6 in below sample.

     class Program
        {
            private static readonly IEnumerable<string> DefaultNamespaces =
                new[]
                {
                    "System", 
                    "System.IO", 
                    "System.Net", 
                    "System.Linq", 
                    "System.Text", 
                    "System.Text.RegularExpressions", 
                    "System.Collections.Generic"
                };
    
            private static string runtimePath = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\{0}.dll";
    
            private static readonly IEnumerable<MetadataReference> DefaultReferences =
                new[]
                {
                    MetadataReference.CreateFromFile(string.Format(runtimePath, "mscorlib")),
                    MetadataReference.CreateFromFile(string.Format(runtimePath, "System")),
                    MetadataReference.CreateFromFile(string.Format(runtimePath, "System.Core"))
                };
    
            private static readonly CSharpCompilationOptions DefaultCompilationOptions =
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                        .WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Release)
                        .WithUsings(DefaultNamespaces);
    
            public static SyntaxTree Parse(string text, string filename = "", CSharpParseOptions options = null)
            {
                var stringText = SourceText.From(text, Encoding.UTF8);
                return SyntaxFactory.ParseSyntaxTree(stringText, options, filename);
            }
    
            static void Main(string[] args)
            {
                var fileToCompile = @"C:\Users\DesktopHome\Documents\Visual Studio 2013\Projects\ConsoleForEverything\SignalR_Everything\Program.cs";
                var source = File.ReadAllText(fileToCompile);
                var parsedSyntaxTree = Parse(source, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
    
                var compilation
                    = CSharpCompilation.Create("Test.dll", new SyntaxTree[] { parsedSyntaxTree }, DefaultReferences, DefaultCompilationOptions);
                try
                {
                    var result = compilation.Emit(@"c:\temp\Test.dll");
    
                    Console.WriteLine(result.Success ? "Sucess!!" : "Failed");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                Console.Read();
            }
    

    This would need little tweaks but it should give you desired results. Change it as you may wish.

    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
提交回复
热议问题