Visual Studio可以像app.config一样自动调整其他文件的名称吗?



将应用程序配置文件添加到Visual Studio中的.Net项目时,该文件将被命名为app.config,并将重命名(在构建时)为ApplicationName.config

我有一个包含大约 40 个项目的解决方案。我想为其中的很多添加log4net功能。因此,对于每个项目,我都会添加一个文件app.log4net。然后,我将声明一个像这样的构建后事件:

copy $(ProjectDir)app.log4net $(TargetPath).log4net

这很好用。但我想知道是否有一种内置方法可以在没有显式构建后事件的情况下实现相同的目标。

编辑:虽然我喜欢JaredPar和Simon Mourier提出的两种解决方案,但它们并没有提供我所希望的。为此使用自定义工具或 MsBuild 规则会降低其透明度(对于项目的其他程序员),或者至少比使用我当前使用的构建后事件更复杂。尽管如此,我觉得MsBuild将是解决类似问题的正确地方。

在这种情况下,更新app.config名称的不是Visual Studio,而是独立于Visual Studio的核心MSBuild规则。 如果要模拟 app.config 模型,这是您应该采用的方法

控制 app.config 复制的构建序列的两个部分位于 Microsoft.Common.targets 中。

首先计算文件名

<ItemGroup>
    <AppConfigWithTargetPath Include="$(AppConfig)" Condition="'$(AppConfig)'!=''">
        <TargetPath>$(TargetFileName).config</TargetPath>
    </AppConfigWithTargetPath>
</ItemGroup>

接下来,它实际上是作为构建的一部分复制的

<Target
    Name="_CopyAppConfigFile"
    Condition=" '@(AppConfigWithTargetPath)' != '' "
    Inputs="@(AppConfigWithTargetPath)"
    Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
    <!--
    Copy the application's .config file, if any.
    Not using SkipUnchangedFiles="true" because the application may want to change
    the app.config and not have an incremental build replace it.
    -->
    <Copy
        SourceFiles="@(AppConfigWithTargetPath)"
        DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')"
        OverwriteReadOnlyFiles="$(OverwriteReadOnlyFiles)"
        Retries="$(CopyRetryCount)"
        RetryDelayMilliseconds="$(CopyRetryDelayMilliseconds)"
        UseHardlinksIfPossible="$(CreateHardLinksForAdditionalFilesIfPossible)"
        >
        <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
    </Copy>
</Target>

我认为它对于 app.config 来说是非常硬编码的(您可以尝试其他名称 xxx.config,但它不起作用)。

您可以在没有后期构建事件的情况下获得相同的结果,但使用您将为 .log4net 文件选择的自定义工具。请参阅以下示例:编写自定义工具以生成 Visual Studio .NET 代码和开发 Visual Studio 自定义工具

最新更新