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

ASP.NET
c# Random快速连续产生相同随机数的解决方案
form身份验证通过后,只能用FormsAuthentication.RedirectFromLoginPage
ASP.NET Global.asax应用程序文件简介
Asp.net下载功能的解决方案代码
asp.net 生成数字和字母组合的随机数
asp.net显示页面执行时间
DiscuzNT 论坛与主站的同步登录与退出
c# 读取Northwind数据库image字段
asp.net 数据访问层基类
C# 文件保存到数据库中或者从数据库中读取文件
ASP.NET 防止用户跳过登陆界面
asp.net 字符串加密解密技术
asp.net 票据简单应用
基于C# 网站地图制作
asp.net GridView 中增加记录的方法
asp.net 自动将汉字转换成拼音第一个字母
运行asp.net时出现 http错误404-文件或目录未找到
System.Runtime.InteropServices.COMException的解决方法
VS2005 180天限制破解方法
asp.net 面试+笔试题目

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


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

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

如果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> 

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