You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6:将外部目录完整复制到发布文件夹的方法

解决dotnet publish时保留外部目录结构的问题

你当前的配置仅指定了要复制的文件,但未定义这些文件在发布目录中的目标路径,导致所有文件被直接复制到发布根目录。要保留documents-templates的完整目录结构,可通过以下两种MSBuild配置实现:

通过<Link>定义文件在输出目录中的虚拟路径,保留源目录的层级结构:

<ItemGroup>
  <Content Include="D:\Workspace\OtherProject\documents-templates\**">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <Link>documents-templates\%(RecursiveDir)%(Filename)%(Extension)</Link>
  </Content>
</ItemGroup>
  • %(RecursiveDir)会保留源文件的子目录结构,配合前缀documents-templates\,所有文件将被放置在发布目录的documents-templates文件夹下,内部子目录也会同步保留。

方法二:使用<TargetPath>属性(针对发布场景更直接)

通过<CopyToPublishDirectory>专门控制发布阶段的复制行为,<TargetPath>明确指定目标路径:

<ItemGroup>
  <Content Include="D:\Workspace\OtherProject\documents-templates\**">
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    <TargetPath>documents-templates\%(RecursiveDir)%(Filename)%(Extension)</TargetPath>
  </Content>
</ItemGroup>
  • <CopyToPublishDirectory>仅作用于发布流程,避免对日常构建输出产生额外影响;<TargetPath>确保文件按预期的目录结构复制到发布文件夹。

执行dotnet publish命令后,发布目录下会生成完整的documents-templates文件夹,包含源目录的所有文件及子目录结构。

内容的提问来源于stack exchange,提问作者Cloud-Lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:45:33