スポンサーリンク

Memo: Roslynを使ってC#のコードでC#のコードをコンパイルする

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace RoslynComple
{
    class Program
    {
        private static readonly IEnumerable<string> DefaultNamepaces = 
            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.8\{0}.dll";
        private static readonly IEnumerable<MetadataReference> DefaultRefrences =
            new[]
            {
                MetadataReference.CreateFromFile(string.Format(runtimePath, "mscorlib")),
                MetadataReference.CreateFromFile(string.Format(runtimePath, "System")),
                MetadataReference.CreateFromFile(string.Format(runtimePath, "System.Core"))
            };

        private static readonly CSharpCompilationOptions DefaultCompletionOpsions =
            new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                    .WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Release)
                    .WithUsings(DefaultNamepaces);
        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)
        {
            // DLL Source Code
            var fileToCompile = @"C:\temp\Test.cs";
            var source = File.ReadAllText(fileToCompile);
            var parseSyntaxTree 
                = Parse(source, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3));
            var compliation 
                = CSharpCompilation.Create("test.dll", 
                                            new SyntaxTree[] { parseSyntaxTree }, 
                                            DefaultRefrences, DefaultCompletionOpsions);
            try
            {
                var result = compliation.Emit(@"c:\temp\Test.dll");
                Console.WriteLine(result.Success ? "Sucess!!" : "Failed");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            Console.Read();
        }
    }
}

nugetでMicrosoft.CodeAnalysis.CSharpの追加が必要。(その他依存関係にあるパッケージも。)

参考:

コメント

タイトルとURLをコピーしました