ConfigurationManager读取配置文件

App.config文件有如下内容: 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>
    <appSettings>
        <add key="userName" value="Gaby"/>
        <add key="password" value="12345"/>
    </appSettings>
    <connectionStrings>
        <add name="constr" connectionString="server=.;database=testDB;uid=sa;pwd=123"/>
    </connectionStrings>

</configuration>

 

 

AppSettingsSection 对象包含配置文件的 appSettings 节的内容

var userName = ConfigurationManager.AppSettings["username"];

var pwd = ConfigurationManager.AppSettings["password"];

注: 必须引入using System.Configuration的DLL。

 

 

 

读取数据库连接字符串connectionStrings 节的内容
  ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;

 var conStr = connections["constr"];

 

以下是返回集合:

// Show how to use ConnectionStrings.

static void DisplayConnectionStrings()

{

// Get the ConnectionStrings collection.

ConnectionStringSettingsCollection connections =

ConfigurationManager.ConnectionStrings;

Console.WriteLine();

Console.WriteLine("Connection strings:");

// Loop to get the collection elements.

IEnumerator conEnum =

connections.GetEnumerator();

int i = 0;

while (conEnum.MoveNext())

{

string name = connections[i].Name;

string connectionString = connections[name].ConnectionString;

string provider = connections[name].ProviderName;

Console.WriteLine("Name:               {0}", name);

Console.WriteLine("Connection string:  {0}", connectionString);

Console.WriteLine("Provider:           {0}", provider);

}

} 

 

 

 

你可能感兴趣的:(configuration)