Skip to main content
 首页 » 编程设计

c#之如何使 Roslyn Compilation 复制引用

2024年02月05日10fff_TT

使用 Roslyn 编译项目时一切正常,但由于项目引用了其他程序集,我需要将它们复制到输出目录

我有这个代码:

var workspace = MSBuildWorkspace.Create(); 
 
var projects = workspace.OpenSolutionAsync(@"Solution.sln").Result; 
 
var project = projects.Projects.First(); 
 
var compilation = project.GetCompilationAsync().Result; 
 
var dllPath = Path.Combine(Directory.GetCurrentDirectory(), "Example.dll"); 
var pdbPath = Path.Combine(Directory.GetCurrentDirectory(), "Example.pdb"); 
 
  using (FileStream dllStream = new FileStream(dllPath, FileMode.OpenOrCreate)) 
    using (FileStream pdbStream = new FileStream(pdbPath, FileMode.OpenOrCreate)) 
    { 
      var emit = compilation.Emit(dllStream, pdbStream); 
    } 
 
var assembly = Assembly.LoadFile(dllPath); 

当然它只写 Example.dll 但我没有找到告诉编译或发出的选项来添加 CopyLocal 的引用等(以自动方式)而不需要循环引用并自己做

请您参考如下方法:

Roslyn 永远不会复制引用。那不是编译器做的事情。在常规构建中,MSBuild 决定是否在本地复制引用。

如果您想要复制引用,那是您的代码需要处理的事情。