app.config 新 .csproj 格式的文件

app.config file in the new .csproj format

Visual studio 提供了精简的 .csproj 文件格式。

我正在尝试构建 .NET Framework 应用程序(版本 4.6.1),但使用新的可手动编辑的文件。

与之前的行为类似,我希望将 app.config 文件复制到输出目录,但重命名为 <output_exe>.config(其中 output_exe 是可执行文件的名称)。

我们在 .csproj 文件中放入什么才能发生这种情况?

这不起作用,因为它不会重命名文件:

<ItemGroup>
  <Content Include="App.config">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>

尝试添加如下脚本来完成这项工作:

  <ItemGroup>
    <Content Include="App.config">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <Target Name="MyCustomTarget" AfterTargets="build">
    <Move SourceFiles="$(OutputPath)\App.config" DestinationFiles="$(OutputPath)$(AssemblyName).config" />
  </Target>

第一个脚本可以确保 App.config 文件将被复制到输出文件夹,第二个脚本将在构建目标后使用 AssemblyName(可执行文件的名称)重命名文件。

更多详情:如果我们需要ProjectName.exe.config,那么使用$(OutputPath)$(AssemblyName).exe.config。如果我们需要ProjectName.config,那么使用$(OutputPath)$(AssemblyName).config。我们可以根据需要自定义改名文件的格式。

只需添加 msbuild 和工具期望此功能的 AppConfig 属性:

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net472</TargetFramework>
    <AppConfig>App.config</AppConfig>
  </PropertyGroup>

</Project>

这使 PrepareForBuild msbuild 目标能够自动选取文件,后续构建步骤也可以将此文件编辑为逻辑文件 - 例如SDK 将根据定义的 TargetFramework 修改 startup/supportedRuntime 部分。将其添加为自定义项目或构建步骤将失去此能力。