asp.net 讀取設定檔方法_實用技巧

來源:互聯網
上載者:User
方法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。
不同的type不但設定配置節的方式不一樣,最後訪問設定檔的操作上也有差異。下面我們就舉一個設定檔的例子,讓它包含這三個不同的type。
複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>
<section name="Test2" type="System.Configuration.DictionarySectionHandler"/>
<section name="Test3" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Test1 setting1="Hello" setting2="World"/>
<Test2>
<add key="Hello" value="World" />
</Test2>
<Test3>
<add key="Hello" value="World" />
</Test3>
</configuration>

我們對上面的自訂配置節進行說明。在聲明部分使用<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>聲明了一個配置節它的名字叫 Test1,類型為SingleTagSectionHandler。在設定配置節部分使用 <Test1 setting1="Hello" setting2="World"/>設定了一個配置節,它的第一個設定的值是Hello,第二個值是World,當然還可以有更多。其它的兩個配 置節和這個類似。
下面我們看在程式中如何訪問這些自訂的配置節。我們用過ConfigurationSettings類的靜態方法GetConfig來擷取自訂配置節的資訊。
public static object GetConfig(string sectionName);
下面是訪問這三個配置節的代碼:
複製代碼 代碼如下:

//訪問配置節Test1
IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("Test1");
string str = (string)IDTest1["setting1"] +" "+(string)IDTest1["setting2"];
MessageBox.Show(str); //輸出Hello World
//訪問配置節Test1的方法2
string[] values1=new string[IDTest1.Count];
IDTest1.Values.CopyTo(values1,0);
MessageBox.Show(values1[0]+" "+values1[1]); //輸出Hello World
//訪問配置節Test2
IDictionary IDTest2 = (IDictionary)ConfigurationSettings.GetConfig("Test2");
string[] keys=new string[IDTest2.Keys.Count];
string[] values=new string[IDTest2.Keys.Count];
IDTest2.Keys.CopyTo(keys,0);
IDTest2.Values.CopyTo(values,0);
MessageBox.Show(keys[0]+" "+values[0]);
//訪問配置節Test3
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); //輸出Hello World

通過上面的代碼我們可以看出,不同的type通過GetConfig返回的類型不同,具體獲得配置內容的方式也不一樣。 配置節處理常式
傳回型別
複製代碼 代碼如下:

SingleTagSectionHandler
Systems.Collections.IDictionary
DictionarySectionHandler
Systems.Collections.IDictionary
NameValueSectionHandler
Systems.Collections.Specialized.NameValueCollection

3.2 自訂配置節組
配置節組是使用<sectionGroup>元素,將類似的配置節分到同一個組中。配置節組聲明 部分將建立配置節的包含元素,在<configSections>元素中聲明配置節組,並將屬於該組的節置於< sectionGroup>元素中。下面是一個包含配置節組的設定檔的例子:
複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="TestGroup">
<section name="Test" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<TestGroup>
<Test>
<add key="Hello" value="World"/>
</Test>
</TestGroup>
</configuration>

下面是訪問這個配置節組的代碼:
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); //輸出Hello World
C# 解析設定檔內容 System.Configuration
1. 建立配置節類
必須建立繼承自ConfigurationSection的對象才能進行配置資料讀寫操作,ConfigurationSection提供了索引器用來擷取和設定配置資料,需要注意的是擁有ConfigurationProperty特性的屬性才會被儲存,並且名稱要保持大小寫完全一致,如下面的代碼中,所有的"id"必須保持一樣。
複製代碼 代碼如下:

class ConfigSectionData : ConfigurationSection
{
[ConfigurationProperty("id")]
public int Id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[ConfigurationProperty("time")]
public DateTime Time
{
get { return (DateTime)this["time"]; }
set { this["time"] = value; }
}
}

2. 建立設定檔操作對象
複製代碼 代碼如下:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);

上面的例子是操作 app.config,在根節點(configuration)下寫入名稱為"add"的配置資料。
複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="add" type="ConsoleApplication1.ConfigSectionData, ... />
</configSections>
<add id="1000" time="02/18/2006 21:51:06" />
</configuration>

需要注意的 VS2005 在IDE模式下會將資訊寫入 *.vshost.exe.config,並且在程式關閉時覆寫該檔案,因此您可能看不到您寫入的配置資料,只要在資源管理其中執行 *.exe 檔,您就可以在 *.exe.config 檔案中看到結果了。
如果我們需要操作非預設設定檔,可以使用ExeConfigurationFileMap對象。
複製代碼 代碼如下:

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);

如果我們不希望在根節點下寫入配置資料,可以使用ConfigurationSectionGroup對象。
複製代碼 代碼如下:

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
config.SectionGroups.Add("group1", new ConfigurationSectionGroup());
config.SectionGroups["group1"].Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);

下面就是產生的設定檔。
複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="group1" type="System.Configuration.ConfigurationSectionGroup, ... >
<section name="add" type="ConsoleApplication1.ConfigSectionData, ... />
</sectionGroup>
</configSections>
<group1>
<add id="1000" time="02/18/2006 22:01:02" />
</group1>
</configuration>

3. 讀取設定檔
複製代碼 代碼如下:

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = config.SectionGroups["group1"].Sections["add"] as ConfigSectionData;
//ConfigSectionData data = config.Sections["add"] as ConfigSectionData; // 從根節讀取
if (data != null)
{
Console.WriteLine(data.Id);
Console.WriteLine(data.Time);
}

4. 寫設定檔
在寫入 ConfigurationSectionGroup 和 ConfigurationSection 前要判斷同名配置是否已經存在,否則會寫入失敗。
另外如果設定檔被其他Configuration對象修改,則儲存會失敗,並拋出異常。建議採用Singleton模式。
複製代碼 代碼如下:

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 2000;
data.Time = DateTime.Now;
ConfigurationSectionGroup group1 = config.SectionGroups["group1"];
if (group1 == null)
config.SectionGroups.Add("group1", new ConfigurationSectionGroup());
ConfigurationSection data = group1.Sections["add"] as config;
if (add == null)
config.SectionGroups["group1"].Sections.Add("add", data);
else
{
group1.Sections.Remove("add");
group1.Sections.Add("add", data);
// 或者直接修改原設定物件,前提是類型轉換要成功。
//ConfigSectionData configData = add as ConfigSectionData;
//configData.Id = data.Id;
//configData.Time = data.Time;
}
config.Save(ConfigurationSaveMode.Minimal);

5. 刪除配置節
複製代碼 代碼如下:

刪除ConfigurationSectionGroup
config.SectionGroups.Remove("group1");
//config.SectionGroups.Clear();
config.Save(ConfigurationSaveMode.Minimal);
刪除ConfigurationSection
config.Sections.Remove("add1");
//config.Sections.Clear();
if (config.SectionGroups["group1"] != null)
{
config.SectionGroups["group1"].Sections.Remove("add2");
//config.SectionGroups["group1"].Sections.Clear();
}
config.Save(ConfigurationSaveMode.Minimal);

6. 其他
可以使用 ConfigurationManager.OpenMachineConfiguration() 來操作 Machine.config 檔案。
或者使用 System.Web.Configuration 名字空間中的 WebConfigurationManager 類來操作 ASP.net 設定檔。
ConfigurationManager還提供了AppSettings、ConnectionStrings、GetSection()等便捷操作。
7. 使用自訂類
可以使用自訂類,不過需要定義一個轉換器。
複製代碼 代碼如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
// 要寫入設定檔的自訂類
class CustomData
{
public CustomData(string s)
{
this.s = s;
}
private string s;
public string S
{
get { return s; }
set { s = value; }
}
}
// 自訂的轉換器(示範代碼省略了類型判斷)
class CustomConvert : ConfigurationConverterBase
{
public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)
{
return (type == typeof(string));
}
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
return (value as CustomData).S;
}
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
return new CustomData((string)data);;
}
}
class ConfigSectionData : ConfigurationSection
{
[ConfigurationProperty("id")]
public int Id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[ConfigurationProperty("time")]
public DateTime Time
{
get { return (DateTime)this["time"]; }
set { this["time"] = value; }
}
[ConfigurationProperty("custom")]
[TypeConverter(typeof(CustomConvert))] // 指定轉換器
public CustomData Custom
{
get { return (CustomData)this["custom"]; }
set { this["custom"] = value; }
}
}
public class Program
{
static void Main(string[] args)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
data.Custom = new CustomData("abcdefg...");
config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);
// 讀取測試
ConfigSectionData configData = (ConfigSectionData)config.Sections["add"];
Console.WriteLine(configData.Custom.S);
}
}

儲存後的設定檔
複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="add" type="..." />
</configSections>
<add id="1000" time="04/17/2006 22:06:58" custom="abcdefg..." />
</configuration>

更詳細的資訊可以看 MSDN 中關於 System.Configuration.ConfigurationConverterBase 的說明。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.