如何从c#中的web.config访问默认连接字符串

时间:2017-09-28 09:56:28

标签: c# sql web-config connection-string app-config

我的配置文件包含以下配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />
  </configSections>
  <dataConfiguration defaultDatabase="myConnectionString" />
  <connectionStrings>
    <add name="myConnectionString" connectionString="Data Source=mydatasource;Max Pool Size=100;Pooling=true; Initial Catalog=MyDB;User ID=Myuser;Password=Password;Connection Timeout=60" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>

正如您所看到的,我已将默认dataconfiguration设置为使用myConnectionString作为默认连接字符串,但在代码隐藏(c#)后如何访问此连接字符串而无需提供名称即myConnectionString

所以在下面的代码中:

string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

SqlConnection cnn = new SqlConnection(connectionString);

SqlBulkCopy sbc = new SqlBulkCopy(cnn);

我想跳过硬编码连接字符串的名称。

1 个答案:

答案 0 :(得分:3)

var dataConfig = (Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings)System.Configuration.ConfigurationManager.GetSection(
    "dataConfiguration");

string connectionString = ConfigurationManager.ConnectionStrings[dataConfig.DefaultDatabase].ConnectionString;

这是我从自定义配置节和DatabaseSettings类的典型用法中可以看出的。

编辑:我已经使用您的确切app.config在LINQPad中对其进行了测试,得到了结果:

Data Source=mydatasource;Max Pool Size=100;Pooling=true; Initial Catalog=MyDB;User ID=Myuser;Password=Password;Connection Timeout=60