* 读取App.config配置文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="hxh" connectionString="Server=DESKTOP-OCGH29Q;database=xx;integrated security=true;Connection Timeout=30;" providerName="System.Data.SqlClient" /> </connectionStrings> <appSettings> <add key="key1" value="value1" /> <add key="key2" value="value2" /> </appSettings> </configuration>
App.config文件的特点:
- 有一个<configuration>...</configuration>节点,所有的配置都在里面;
- c#有一个内置的<connectionStrings>节点,用来存放数据库连接字符串;
using System.Configuration; // 按数字循环得到一个个ConnectionStringSettings对象 // 每个ConnectionStringSettings对象有Name和ConnectionString属性 for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++) { string name = ConfigurationManager.ConnectionStrings[i].Name; string connectionString = ConfigurationManager.ConnectionStrings[i].ConnectionString; } //也可以如下操作,使用ConnectionStringSettings类型来进行foreach遍历 foreach (ConnectionStringSettings conn in ConfigurationManager.ConnectionStrings) { string name = conn.Name; string connectionString = conn.ConnectionString; } //直接获取conn的值 ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
//AppSettings是NameValueConnection类型,使用AllKeys返回一个所有Key组成的字符串数组;没有NameValuePair这样的对象,所以无法使用foreach来进行循环 string[] keys = ConfigurationManager.AppSettings.AllKeys; for (int i = 0; i < keys.Length; i++) { string key = keys[i]; //通过Key来索引Value string value = ConfigurationManager.AppSettings[key]; } //直接获取key的值 ConfigurationManager.AppSettings["key1"]