【问题标题】:Embedded files with Roslyn compilation带有 Roslyn 编译的嵌入式文件
【发布时间】:2019-11-15 03:23:07
【问题描述】:

我正在寻找如何使用 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 ...
    }
}

【问题讨论】:

    标签: c# roslyn embedded-resource


    【解决方案1】:

    是的,可以使用 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在编译后被正确处理。

    【讨论】:

      猜你喜欢
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多