【问题标题】:Getting Connectionstring values from Other config file in subfolders and add the connectionstring to the root app.config file从子文件夹中的其他配置文件获取连接字符串值并将连接字符串添加到根 app.config 文件
【发布时间】:2015-06-02 15:49:13
【问题描述】:

我正在使用一个 Windows 应用程序,其中我的配置文件(dev.configprod.configuat.config)位于多个文件夹中,例如 devproduat。我想根据特定文件夹中的特定条件获取特定的配置文件值,例如connectionstrings,并且我想在根app.config 文件中添加相应的connectionstrings。然后我需要根据添加的连接字符串获取数据。谁能帮我解决这个问题?

【问题讨论】:

    标签: c# .net visual-studio visual-studio-2008


    【解决方案1】:

    可以很容易做到的是外部化您的连接字符串(我们倾向于将它们放入App_Data\config,因为该文件夹受 IIS 保护,并且没有任何来自尝试浏览时将返回该文件夹)

    所以在你的 main web.config 中,你会有这样的东西:

    <connectionStrings configSource="App_Data\config\dev.config" />
    

    然后你去测试,你只要把它改成

    <connectionStrings configSource="App_Data\config\uat.config" />
    

    在您的个人配置文件中,您只有一个部分:

    dev.config:

    <connectionStrings>
       <add name="SomeName"
            connectionString="server=.;database=test;integrated Security=SSPI;"
            providerName="System.Data.SqlClient" />
       ......
    </connectionStrings>
    

    【讨论】:

      【解决方案2】:

      您可以使用 ExeConfigurationFileMap 和 ConfigurationManager.OpenMappedExeConfiguration() 根据条件加载自定义配置文件。

      ExeConfigurationFileMap configFileMap = ExeConfigurationFileMap("path/to/custom.config");
      System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)
      

      当您拥有配置对象后,您可以选择您需要的给定部分,在您的情况下为connectionstrings

      ConnectionStringsSection connectionStrings = config.ConnectionStrings;
      

      然后你可以根据你想要的条件加载你想要的任何配置文件,并选择你想要的部分。

      关于ConnectionStringsSection with a short example (MSDN)的更多信息。

      【讨论】:

        猜你喜欢
        • 2015-01-10
        • 2020-06-25
        • 1970-01-01
        • 2015-12-25
        • 2015-01-31
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 2020-03-17
        相关资源
        最近更新 更多