当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET 遍历配置文件的连接字符串

ASP.NET
.net基础知识错误注意二十二点知识
用.NET动态创建类的实例讲解
微软发布.NET Framework 3.5 SP1正式版
asp.net教程:HTTP状态码200,301,302
.NET 2.0中Hashtable快速查找的方法
在ASP.Net Ajax中调用WebService
asp.net 和 access 联合开发的分页类
ASP.NET 全局异常处理
用SQL语句完成SQL Server数据库的修复
.net 框架程序设计
ASP.NET结合XML编写计数器
ASP.NET水晶报表实现打印功能
Asp.Net中设计与使用水晶报表
防止ASP.NET按钮多次提交的办法
.NET开发事件处理的步骤
ASP.NET刷新页面的六种方法
Asp.net ajax实现任务提示页面
ASP.NET 2.0中XML数据的处理
ASP.NET中XML数据的处理
Jadu: 将 PHP 编译成 .NET

ASP.NET 遍历配置文件的连接字符串


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 133 ::
收藏到网摘: n/a

在ASP.NET 2.0中,提供了更方便的配置文件访问的类,具体可以到 System.Configuration 名称空间下进行查看。本文提供一种在开发过程中常用的得到数据库字符串的方法,为方便使用,写成一个方法进行调用:

  

以下为引用的内容:
public string GetConnectionString( string _connectionStringsName )

  {

  System.Configuration.ConnectionStringSettingsCollection config = System.Configuration.ConfigurationManager.ConnectionStrings;

  for (int i = 0 ; i < config.Count ; i++)

  {

  if (config[i].Name.Equals(_connectionStringsName, StringComparison.OrdinalIgnoreCase))

  return config[i].ToString();

  }

  return String.Empty;

  }

 
如果web.config配置如下:

以下为引用的内容:

<connectionStrings>

<add name="ConnectionString1" connectionString="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=DataBase1;Server=(local);" providerName="System.Data.SqlClient"/>

<add name="ConnectionString2" connectionString="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=DataBase2;Server=(local);" providerName="System.Data.SqlClient"/>

</connectionStrings>

如果写成静态类方法,则可以使用下面的方法进行调用:

以下为引用的内容:
string ConnectString = XianhuiMengUtil.GetConnectionString("ConnectionString1");
 
另外,如果在遍历时进行输出,则可以看到多出来一个配置项,那是因为machine.config里已经默认定义理一个数据库连接,内容如下:

以下为引用的内容:

<connectionStrings>

<add name="LocalSqlServer" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename= DataDirectory aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />

</connectionStrings>


 
这就是许多网友在论坛上经常会问:为什么我的程序会调用 SQLEXPRESS 数据库的原因,如果你的数据库配置不正确,或者无法打开时,就会使用 SQLEXPRESS 数据库。