.NET配置文件中的连接字符串
不推薦在web.config中使用appSettings部分。而是使用web.config中的connectionStrings部分。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
</configuration>
要将连接字符串读入代码中,请使用ConfigurationManager类。
string connStr = ConfigurationManager.ConnectionStrings[“myConnectionString”].ConnectionString;
记住要添加对System.Configuration组件的引用。然后包括名称空间System.Configuration以获得对ConfigurationManager类的访问。
// C#
using System.Configuration;
// VB.Net
imports System.Configuration
清除来自高级配置文件的连接字符串
配置文件是分层的,其中machine.config位于最高级别。您可以清除在层次结构中较早定义的连接字符串,以确保任何不需要的设置不会冒泡达到所需的值。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<clear /> <!-- clear all other connection strings -->
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
</configuration>
通常,在connectionStrings部分的顶部添加是确保没有其他连接字符串从更高级别的配置文件冒泡的好习惯。
.NET 2.0配置文件之前的连接字符串
仅对旧的.NET 1.0和.NET 1.1应用程序使用此信息。在appSettings位置中,添加一个名为您想要引用连接字符串的键。
<appSettings>
<add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</appSettings>
要从代码读取连接字符串,请使用ConfigurationSettings类。
string connStr = ConfigurationSettings.AppSettings(“myConnectionString”);
现在,您已将连接字符串从web.config加载到代码中的字符串变量中。