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

如何在ASP.NET Core中自定义发布文件存放目录并分类存放?

如何在ASP.NET Core发布时自定义文件存放目录

要实现发布时将DLL、JSON等文件分类存放到独立文件夹,核心是通过修改项目的.csproj文件配置发布规则,以下是具体实现方案:

方案1:按文件类型拆分到独立文件夹

比如将所有DLL文件放到bin目录,非配置类JSON文件放到config目录,保留主程序文件(exe、web.config等)在根目录,配置示例如下:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <!-- 将所有非wwwroot下的DLL文件输出到bin目录 -->
  <ItemGroup>
    <PublishFile Include="**\*.dll" Exclude="**\wwwroot\**">
      <DestinationSubDirectory>bin\</DestinationSubDirectory>
    </PublishFile>
  </ItemGroup>

  <!-- 将非wwwroot、非appsettings系列的JSON文件输出到config目录 -->
  <ItemGroup>
    <PublishFile Include="**\*.json" Exclude="**\wwwroot\**;appsettings*.json">
      <DestinationSubDirectory>config\</DestinationSubDirectory>
    </PublishFile>
  </ItemGroup>

  <!-- 保留主程序文件(exe、web.config、pdb等)在根目录 -->
  <ItemGroup>
    <PublishFile Include="**\*.exe;**\*.config;**\*.pdb" Exclude="**\wwwroot\**">
      <DestinationSubDirectory>\</DestinationSubDirectory>
    </PublishFile>
  </ItemGroup>

</Project>

配置说明

  • <PublishFile>:指定发布时需要处理的文件集合
  • <DestinationSubDirectory>:设置文件发布后的目标子目录,根目录用\表示
  • Exclude:排除不需要按规则处理的文件,比如wwwroot下的静态资源、需要保留在根目录的appsettings配置文件

方案2:指定特定文件组移至单独目录

如果只需要将某几个特定文件移到目标目录,比如把MyApp.Core.dll和MyApp.Data.dll放到libs目录,添加以下配置即可:

<ItemGroup>
  <PublishFile Include="MyApp.Core.dll;MyApp.Data.dll">
    <DestinationSubDirectory>libs\</DestinationSubDirectory>
  </PublishFile>
</ItemGroup>

注意事项

  1. 配置文件路径适配:如果将JSON配置文件移到了config目录,需要在Program.cs中修改配置加载路径,确保程序能正常读取:
var builder = WebApplication.CreateBuilder(args);

// 加载config目录下的配置文件
builder.Configuration.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"config/appsettings.{builder.Environment.EnvironmentName}.json", optional: true);
  1. 测试发布效果:修改.csproj后,可通过dotnet publish命令或Visual Studio的发布功能验证输出目录结构是否符合预期。

内容的提问来源于stack exchange,提问作者Reza Yousefi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:24:27