C#: 为控制台或窗口应用程序转换多个配置

对于那些在 ASP.Net 中做 WEB 的人,他们知道有多个配置文件的原则:

Web.Config
Web.Debug.Config
Web.Release.Config

Web.Config 文件是用于您自己的开发,Web.Debug.Config 文件是用于测试或开发版本(例如在另一服务器上),而发布版本是用于生产服务器。

但是对于控制台应用程序或 Winform,这种拥有多个配置文件的可能性并不存在,至少不在手边。我将向您展示如何在控制台应用程序或 Winform 或 WPF 中添加此选项。

请准确按照以下步骤操作:

1. 在 Visual Studio 中,在您的原始 App.Config 下面创建一个 App.Debug.Config 或 App.Release.Config 文件

2. 右键单击您的项目,然后点击“Unload Project”(英文),我不知道法语翻译,但应该是类似“卸载项目”的东西

3. 然后在项目上,右键单击并选择“Edit”或“编辑” .csproj 或 .vbproj

4. 在最后一个 PropertyGroup : 下面复制这些行:

 
 
 
<PropertyGroup>
  <ProjectConfigFileName>App.config</ProjectConfigFileName>
</PropertyGroup>

5. 在 ItemGroup 部分找到 (您要找的),修改并添加以下块 ,当然,如果您只使用一个或多个附加配置文件,您可以添加这些新块以对应您的文件,并且不要忘记更改名称:

 
 
 
 
 
 
 
 
 
<ItemGroup>
   <NoneInclude="App.config"/>
   <NoneInclude="App.Debug.config">
     <DependentUpon>App.config</DependentUpon>
   </None>
   <NoneInclude="App.Release.config">
     <DependentUpon>App.config</DependentUpon>
   </None>
 </ItemGroup>

6. 在最后一个 Import 标签下面复制以下内容:

 
<ImportProject="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v15.0\Web\Microsoft.Web.Publishing.targets"/>

对于 Visual Studio 2017,版本是 v15.0,但如果您使用的是 Visual Studio 2019,您需要将 v15.0 替换为 v16.0(对于 VS2015 = v14.0 和 VS2013 = v12.0)

您甚至可以在您的 PC 上查找 Visual Studio 的版本在这里: 

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v[您的 VISUAL STUDIO 版本]\Web\Microsoft.Web.Publishing.targets

7. 在您的文件末尾添加此内容,在 </Project> 标签之前

 
 
 
<TargetName="AfterBuild">
  <TransformXmlSource="@(AppConfigWithTargetPath)"Transform="$(ProjectConfigTransformFileName)"Destination="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')" />
</Target>

8. 保存所有内容并重新加载您的项目

9. 不要忘记像在 ASP.Net 中一样在您的新配置文件中每个您想要转换的元素后添加标签 xdt:Transform="SetAttributes" xdt:Locator="Match(name)",并且 <configuration> 标签必须具有以下 xdt 架构: xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"

一个例子:

 
<?xmlversion="1.0"?>
 
  <appSettings>
    <addkey="Mode"value="Debug"xdt:Transform="Insert"/>
    <addkey="MyKey"value="123456"xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
  </appSettings>
 
    <connectionStrings>
      <add name="MyDB"
        connectionString="数据源=ReleaseSQLServer;初始目录=MyReleaseDB;集成安全=True"
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
</configuration >
 

Aucun commentaire pour le moment.

Une erreur s'est produite. Cette application peut ne plus répondre jusqu'à ce qu'elle soit rechargée.Veuillez contacter l'auteur. Reload 🗙