C#讀寫config配置檔案
一:使用ConfigurationManager
①:新增System.configguration
②:引用空間
③:config配置檔案配置節
A:自定義配置
B:資料來源配置
<addname="kyd"connectionString=“server=.;database=UFDATA_999_2017;user=sa;pwd=123”/>
</connectionStrings>
- 1
C:普通配置
二:Config檔案讀寫
1.依據連線串名返回字串
A:介面
B:後臺程式碼
private void button1_Click(object sender, EventArgs e)
{
//指定config檔案讀取
string file = System.Windows.Forms.Application.ExecutablePath;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file);
string connectionString =
config.ConnectionStrings.ConnectionStrings[“sql1”].ConnectionString.ToString();
MessageBox.Show( connectionString);
}
2.更新連線字串
A:介面
B:後臺程式碼
private void button2_Click(object sender, EventArgs e)
{
///
///更新連線字串
///
///連線字串名稱
///連線字串內容
///資料提供程式名稱
//指定config檔案讀取
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
bool exist = false; //記錄該連線串是否已經存在 //如果要更改的連線串已經存在 if (config.ConnectionStrings.ConnectionStrings["sql1"] != null) { exist = true; } // 如果連線串已存在,首先刪除它 if (exist) { config.ConnectionStrings.ConnectionStrings.Remove("sql1"); } //新建一個連線字串例項 ConnectionStringSettings mySettings = new ConnectionStringSettings("sql1", "Data","AA"); // 將新的連線串新增到配置檔案中. config.ConnectionStrings.ConnectionStrings.Add(mySettings); // 儲存對配置檔案所作的更改 config.Save(ConfigurationSaveMode.Modified); // 強制重新載入配置檔案的ConnectionStrings配置節 ConfigurationManager.RefreshSection("connectionStrings"); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
3.exe.confing檔案中的appSettings配置節的value
A:介面
B:後臺程式碼
private void button3_Click(object sender, EventArgs e)
{
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == “key1”)
{
MessageBox.Show(config.AppSettings.Settings[“key1”].Value.ToString());
}
}
}
4.exe.confing檔案中的appSettings配置節增加一對鍵值對
A:介面
B:後臺程式碼
private void button4_Click(object sender, EventArgs e)
{
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
bool exist = false;
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == “key1”)
{
exist = true;
}
}
if (exist)
{
config.AppSettings.Settings.Remove(“key1”);
}
config.AppSettings.Settings.Add(“key1”, “5555”);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
}
方法2:
C# 讀寫App.config配置檔案的方法
引用:https://www.cnblogs.com/feiyuhuo/p/5243967.html
一、配置檔案概述:
應用程式配置檔案是標準的 XML 檔案,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置檔案來更改設定,而不必重編譯應用程式。配置檔案的根節點是configuration。我們經常訪問的是appSettings,它是由.Net預定義的配置節。我們經常使用的配置檔案的架構是客訴下面的形式。先大概有個印象,通過後面的例項會有一個比較清楚的認識。下面的“配置節”可以理解為進行配置一個XML的節點。
常見配置檔案模式:
<configuration>
<configSections>//配置節宣告區域,包含配置節和名稱空間宣告
<section> //配置節宣告
<sectionGroup> //定義配置節組
<section> //配置節組中的配置節宣告
<appSettings>//預定義配置節
<Custom element for configuration section>//配置節設定區域
下面是一個最常見的應用程式配置檔案的例子,只有appSettings節:
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="connectionstring" value="User Source=.;Password=123456;Initial Catalog=test;Provider=SQLOLEDB.1;" /> <add key="TemplatePATH" value="Template" /> </appSettings> </configuration>
在預定義的 appSettings 節(注意大小寫),有很多的元素,這些元素名稱都是“add”,有兩個屬性分別是“key”和“value”。
.NET 提供了對appSettings節的訪問方法。在 .NET 1.0 和 1.1 版本中,可以使用 System.Configuration.ConfigurationSettings.AppSettings["Key"] 來對 key = "Key" 的<add>元素的 value屬性 進行訪問。
注意:現在.Net FrameWork 2.0中已經明確表示此ConfigurationSettings屬性已經廢棄,建議改為 ConfigurationManager 或WebConfigurationManager。
使用 System.Configuration.ConfigurationManager,需要在工程裡新增對 system.configuration.dll 程式集的引用。(在解決方案管理器中右鍵點選工程名稱,在右鍵選單中選擇新增引用,在.NET選項卡下即可找到。)
新增引用後,就可以用 ConfigurationManager.AppSettings["Key"] 來讀取對應的值了.
但是,ConfigurationManager.AppSettings 屬性是只讀的,並不支援修改屬性值。這是因為據說微軟不太建議我們動態寫入app.config檔案,而是建議手工配置後,在程式執行時只做靜態訪問。
如果實在需要在程式中進行修改,也即寫入App.Config,請往下看。
二、appSettings配置節的讀寫操作
讀取App.config檔案的appSettings節的方法比較簡單,可以通過上文中System.Configuration.ConfigurationManager.AppSettings["Key"]的方法進行訪問,但前面也已經說了,該方法不提供寫入。
如果希望寫入配置檔案,可以使用ConfigurationManager物件執行開啟配置檔案的操作後,將會返回一個Configuration的物件,利用該物件進行操作(增刪改查都可以哦)。
下面給出實現的程式碼(增加引用using System.Configuration名稱空間)
private void AccessAppSettings() { //獲取Configuration物件 Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //根據Key讀取<add>元素的Value string name = config.AppSettings.Settings["name"].Value; //寫入<add>元素的Value config.AppSettings.Settings["name"].Value = "fx163"; //增加<add>元素 config.AppSettings.Settings.Add("url", "http://www.fx163.net"); //刪除<add>元素 config.AppSettings.Settings.Remove("name"); //一定要記得儲存,寫不帶引數的config.Save()也可以 config.Save(ConfigurationSaveMode.Modified); //重新整理,否則程式讀取的還是之前的值(可能已裝入記憶體) System.Configuration.ConfigurationManager.RefreshSection("appSettings"); }
需要注意的是:
1、根據並不存在的Key值訪問<add>元素,甚至使用remove()方法刪除不存在的元素,都不會導致異常,前者會返回null。
2、add已經存在的<add>元素也不會導致異常,而是concat了已有的Value和新的Value,用","分隔,例如:"olldvalue,newvalue"。
3、在專案進行編譯後,在執行目錄bin\Debuge檔案下,將出現兩個配置檔案,一個名為“ProjectName.exe.config”,另一個名為“ProjectName.vshost.exe.config”。第一個檔案為專案實際使用的配置檔案,在程式執行中所做的更改都將被保存於此;第二個檔案其實為原始碼中“App.config”的同步檔案,在程式執行中不會發生更改。
4、特別注意大小寫(XML檔案是區分大小寫的),例如appSettings配置節。
5、可能有讀者會想到,既然app.config是標準XML,當然也可以用操縱一般XML檔案的方法來讀寫。這當然是可以的!只不過我認為這樣就失去了VS提供app.config檔案的意義了,還不如自己定義一個配置檔案方便。
本文只是粗略地講了app.config檔案中appSettings配置節的訪問方法,connectionStrings配置節的操作基本是類似的,也可以自定義配置節。這些高階的用法可以自己體會,VS對app.config這個配置檔案的管理還是很強大的,例如WinForm應用程式的Settings設定(可以在IDE中或者通過程式碼訪問)其實也是利用了app.config檔案。