使用 Roslyn 编译的嵌入式文件

Embedded files with Roslyn compilation

我正在寻找有关如何使用 Roslyn 编译项目的示例。下面的代码是我在 https://github.com/dotnet/roslyn/wiki/FAQ 中找到的一个例子……这个例子不包括嵌入式文件。这可能吗?

public class MyTask : Task {
    public override bool Execute() {
          var projectFileName = this.BuildEngine.ProjectFileOfTaskNode;
              var project = ProjectCollection.GlobalProjectCollection.
                            GetLoadedProjects(projectFileName).Single();
              var compilation = CSharpCompilation.Create(
                                    project.GetPropertyValue("AssemblyName"),
                                    syntaxTrees: project.GetItems("Compile").Select(
                                      c => SyntaxFactory.ParseCompilationUnit(
                                               c.EvaluatedInclude).SyntaxTree),
                                    references: project.GetItems("Reference")
                                                       .Select(          
                                      r => new MetadataFileReference
                                                   (r.EvaluatedInclude)));
             // Now work with compilation ...
    }
}

是的,可以使用 Roslyn 将资源嵌入到结果程序集中。

要生成结果程序集 CSharpCompilation 类型有一个 Emit 方法。这个方法有很多参数。其中之一是manifestResources,负责添加内嵌资源。您可以根据需要指定任意数量的资源。以下代码演示了如何使用此参数将带有嵌入资源的程序集发送到 peStream。它创建名称为 "resourceName" 且内容位于 "path-to-resource" 路径的资源。

void ProduceAssembly(CSharpCompilation compilation, Stream peStream)
{
    ResourceDescription[] resources =
    {
        new ResourceDescription(
            "resourceName",
            () => File.OpenRead("path-to-resource"),
            isPublic: true
        )
    };
    var result = compilation.Emit(peStream, manifestResources: resources);
    if (!result.Success)
    {
        var diagnostics = string.Join(Environment.NewLine, result.Diagnostics);
        throw new Exception($"Compilation failed with: {diagnostics}");
    }
}

不要忘记检查 EmitResult.Success 属性 以确保编译成功完成。还要确保 peStream 在编译后正确处理。