asp.net 讀取配置文件方法
2024-07-10 12:41:37
供稿:網友
方法1:
代碼如下:
System.Collections.Specialized.NameValueCollection nvc = (System.Collections.Specialized.NameValueCollection)
System.Configuration.ConfigurationManager.GetSection(sectionName);
string keyValue = nvc.GetValues(keyName)[0].ToString();
方法2:
代碼如下:System.Web.Configuration.WebConfigurationManager.AppSettings[keyName].ToString();
參考下面的文章
在C#中如何讀取配置文件
1. 配置文件概述:
應 用程序配置文件是標準的 XML 文件,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置文件來更改設置,而不必重編譯應用程序。配置文件的根節點是 configuration。我們經常訪問的是appSettings,它是由.Net預定義配置節。我們經常使用的配置文件的架構是象下面的形式。先大 概有個印象,通過后面的實例會有一個比較清楚的認識。下面的“配置節”可以理解為進行配置一個XML的節點。
常見配置文件模式:
代碼如下:
<configuration>
<configSections> //配置節聲明區域,包含配置節和命名空間聲明
<section> //配置節聲明
<sectionGroup> //定義配置節組
<section> //配置節組中的配置節聲明
<appSettings> //預定義配置節
<Custom element for configuration section> //配置節設置區域
2. 只有appSettings節的配置文件及訪問方法
下面是一個最常見的應用程序配置文件的例子,只有appSettings節。
代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="connectionstring" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" />
<add key="TemplatePATH" value="Template" />
</appSettings>
</configuration>
下面來看看這樣的配置文件如何方法。
string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];
使用ConfigurationSettings類的靜態屬性AppSettings就可以直接方法配置文件中的配置信息。這個屬性的類型是NameValueCollection。
3. 自定義配置文件
3.1 自定義配置節
一個用戶自定義的配置節,在配置文件中分為兩部分:一是在<configSections></ configSections>配置節中聲明配置節(上面配置文件模式中的“<section>”),另外是在< configSections></ configSections >之后設置配置節(上面配置文件模式中的“<Custom element for configuration section>”),有點類似一個變量先聲明,后使用一樣。聲明一個配置文件的語句如下:
<section name=" " type=" "/>
<section>:聲明新配置節,即可創建新配置節。
name:自定義配置節的名稱。
type:自定義配置節的類型,主要包括System.Configuration.SingleTagSectionHandler、 System.Configuration.DictionarySectionHandler、 System.Configuration.NameValueSectionHandler。