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

ASP.NET
asp.net实现C#代码加亮显示
如何显示在线人数和所在位置
ASP.net生成文字图片
ASP.NET提供文件下载函数
一个简单的ASP.NET Forms 身份认证
在ASP.NET中实现多文件上传
asp.net 2.0中使用sitemapDATAsource做页面导航
通过ASP.net程序创建域帐户故障
为ASP.NET封装的SQL数据库访问类
在ASP.NET中跟踪和恢复大文件下载
SQL存储过程在.NET数据库中的应用
对“学号”、“身份证”的数字分析
把.NET程序部署到没有安装.NET Framwork的机器上
ASP.NET中同时支持简体和繁体中文
几十个ASP.NET性能优化的常用方法
.NET环境下五种邮件发送解决方案
.NET开发中正则表达式中BUG一例
.NET反射、委托技术与设计模式
.net中Windows窗体间的数据交互
ADO.NET访问Oracle 9i存储过程(上)

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


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