C# 在c中按主机名自动加载配置#

C# 在c中按主机名自动加载配置#,c#,app-config,config,C#,App Config,Config,我们在不同的机器上开发一个项目。每台机器都有自己的数据库连接 目前,我们使用外部文件从app.config中加载数据库配置 <connectionStrings configSource="DB.config" /> 有没有一种聪明的方法可以做到这一点?您可以将它添加到每台机器上的machine.config,而不是.config public static string GetConnString() { string connString = ConfigurationS

我们在不同的机器上开发一个项目。每台机器都有自己的数据库连接

目前,我们使用外部文件从
app.config
中加载数据库配置

<connectionStrings configSource="DB.config" />

有没有一种聪明的方法可以做到这一点?

您可以将它添加到每台机器上的machine.config,而不是.config

public static string GetConnString()
{
   string connString = ConfigurationSettings.AppSettings[GetConfigKey("database")];
   return connString;
}

public static string GetConfigKey(string baseKey)
{
   string str = baseKey;
   if (GetHostName().StartsWith("BobsPC"))
   {
       // set str = the appropriate string = DB.[hostname].config
   }
   else if (GetHostName().StartsWith("JacksPC"))
   {
       // set str = the appropriate string = DB.[hostname].config
   }
   return str;
}

保留一个配置文件,并在运行时使用逻辑来检测要使用的配置子集。通常,此语法用于web项目,但您可以调整它以在所有类型的项目中使用

您必须通过添加/更新TransformXml任务来修改项目文件(例如..csproj)。在下面的示例中,转换是在编译期间通过在App.config上应用转换来执行的。如您所见,任务引用$(配置)变量,因此转换命令存储在App.DEBUG.config或App.RELEASE.config中。您可以将其更改为您喜欢的任何msbuild变量。如果我没记错的话,它是$(COMPUTERNAME),所以您必须将转换放在App.MyMachineName.config中

<UsingTask TaskName="TransformXml" 
           AssemblyFile="C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
<Target Name="AfterBuild">
  <!-- use App.$(COMPUTERNAME).config for specific machine configuration -->
  <TransformXml Source="App.config" 
                Condition="Exists('App.$(Configuration).config')" 
                Transform="App.$(Configuration).config" 
                Destination="$(OutDir)$(AssemblyName).dll.config"/>
</Target>

有关详细说明,请参阅

这就是特定于机器的配置:

<?xml version="1.0"?>
<!-- "App.MyMachineName.config" - File name corresponds to the transformation task  -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="MyDbConnection"
         connectionString="Data Source=MyServer;Initial Catalog=MyDb;" 
         providerName="System.Data.SqlClient"
         xdt:Transform="SetAttributes" 
         xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>


我为每台机器配置了不同的.configs。我问的是如何自动收集“正确”的配置您可以尝试在
configSource
中包含一个环境变量,但它很可能会自动扩展它们:
,尽管这个答案需要一些更灵活的代码,我认为这种方法更好,所以您不必为您拥有的每台机器重新编译或重新运行msbuild。
<?xml version="1.0"?>
<!-- "App.MyMachineName.config" - File name corresponds to the transformation task  -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="MyDbConnection"
         connectionString="Data Source=MyServer;Initial Catalog=MyDb;" 
         providerName="System.Data.SqlClient"
         xdt:Transform="SetAttributes" 
         xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>