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