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

ASP.NET
FreeTextBox(版本3.1.6)在ASP.Net 2.0中使用方法
.NET 常用功能和代码小结
在 .NET Framework 2.0 中未处理的异常导致基于 ASP.NET 的应用程序意外退出
asp.net IList查询数据后格式化数据再绑定控件
asp.net sql存储过程
asp.net 简单实现禁用或启用页面中的某一类型的控件
asp.net(c#)获取内容第一张图片地址的函数
The remote procedure call failed and did not execute的解决办法
ASP.NET 在线文件管理
asp.net 读取并修改config文件实现代码
ASP.NET Cookie 操作实现
asp.net Silverlight中的模式窗体
Silverlight中动态获取Web Service地址
asp.net Silverlight应用程序中获取载体aspx页面参数
asp.net 水晶报表隔行换色实现方法
asp.net 获取Gridview隐藏列的值
手动把asp.net的类生成dll文件的方法
asp.net 使用ObjectDataSource控件在ASP.NET中实现Ajax真分页
动态指定任意类型的ObjectDataSource对象的查询参数
asp.net Md5的用法小结

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 80 ::
收藏到网摘: 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 数据库。