App.Config詳解
原文地址:
https://www.cnblogs.com/yoga21/p/9207335.html
應用程式配置檔案是標準的 XML 檔案,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置檔案來更改設定,而不必重編譯應用程式。
配置檔案的根節點是configuration。我們經常訪問的是appSettings,它是由.Net預定義配置節。我們經常使用的配置檔案的架構是象下面的形式。
先大概有個印象,通過後面的例項會有一個比較清楚的認識。下面的“配置節”可以理解為進行配置一個XML的節點。
1. 向專案新增 app.config 檔案:
右擊專案名稱,選擇“新增”→“新增新建項”,在出現的“新增新項”對話方塊中,選擇“新增應用程式配置檔案”;如果專案以前沒有配置檔案,則預設的檔名稱為“ app.config ”,單擊“確定”。出現在設計器檢視中的app.config 檔案為:
<? xml version = "1.0 "encoding = "utf-8 " ?>
< configuration >
</ configuration >
在專案進行編譯後,在 bin/Debuge 檔案下,將出現兩個配置檔案 ( 以本專案為例 ) ,一個名為“JxcManagement.EXE.config ”,另一個名為“ JxcManagement.vshost.exe.config ”。第一個檔案為專案實際使用的配置檔案,在程式執行中所做的更改都將被保存於此;第二個檔案為原始碼“ app.config ”的同步檔案,在程式執行中不會發生更改。
2. connectionStrings 配置節:
請注意:如果您的 SQL 版本為 2005 Express 版,則預設安裝時 SQL 伺服器例項名為localhost/SQLExpress ,須更改以下例項中“ Data Source=localhost; ”一句為“ Data Source=localhost/SQLExpress; ”,在等於號的兩邊不要加上空格。
<!-- 資料庫連線串 -->
< connectionStrings >
< clear />
< add name = "conJxcBook "
connectionString = "Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=******** "
providerName = "System.Data.SqlClient " />
</ connectionStrings >
3. appSettings 配置節:
appSettings 配置節為整個程式的配置,如果是對當前使用者的配置,請使用 userSettings 配置節,其格式與以下配置書寫要求一樣。
<!-- 進銷存管理系統初始化需要的引數 -->
< appSettings >
< clear />
< add key = "userName "value = "" />
< add key = "password "value = "" />
< add key = "Department "value = "" />
< add key = "returnValue "value = "" />
< add key = "pwdPattern "value = "" />
< add key = "userPattern "value = "" />
</ appSettings >
4. 讀取與更新 app.config
對於app.config 檔案的讀寫,參照了網路文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題為“Read/Write App.Config File with .NET 2.0”一文。
請注意:要使用以下的程式碼訪問app.config檔案,除新增引用System.Configuration外,還必須在專案新增對System.Configuration.dll的引用。
4.1 讀取connectionStrings配置節
/// <summary>
/// 依據連線串名字connectionName返回資料連線字串
/// </summary>
/// <param name="connectionName"></param>
/// <returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =
ConfigurationManager .ConnectionStrings[connectionName].ConnectionString.ToString();
Console .WriteLine(connectionString);
return connectionString;
}
4.2 更新connectionStrings配置節
/// <summary>
/// 更新連線字串
/// </summary>
/// <param name="newName"> 連線字串名稱 </param>
/// <param name="newConString"> 連線字串內容 </param>
/// <param name="newProviderName"> 資料提供程式名稱 </param>
private static void UpdateConnectionStringsConfig(string newName,
string newConString,
string newProviderName)
{
bool isModified = false ; // 記錄該連線串是否已經存在
// 如果要更改的連線串已經存在
if (ConfigurationManager .ConnectionStrings[newName] != null )
{
isModified = true ;
}
// 新建一個連線字串例項
ConnectionStringSettings mySettings =
new ConnectionStringSettings (newName, newConString, newProviderName);
// 開啟可執行的配置檔案*.exe.config
Configuration config =
ConfigurationManager .OpenExeConfiguration(ConfigurationUserLevel .None);
// 如果連線串已存在,首先刪除它
if (isModified)
{
config.ConnectionStrings.ConnectionStrings.Remove(newName);
}
// 將新的連線串新增到配置檔案中.
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
// 儲存對配置檔案所作的更改
config.Save(ConfigurationSaveMode .Modified);
// 強制重新載入配置檔案的ConnectionStrings配置節
ConfigurationManager .RefreshSection("ConnectionStrings" );
}
4.3 讀取appStrings配置節
/// <summary>
/// 返回*.exe.config檔案中appSettings配置節的value項
/// </summary>
/// <param name="strKey"></param>
/// <returns></returns>
private static string GetAppConfig(string strKey)
{
foreach (string key in ConfigurationManager .AppSettings)
{
if (key == strKey)
{
return ConfigurationManager .AppSettings[strKey];
}
}
return null ;
}
4.4 更新connectionStrings配置節
/// <summary>
/// 在*.exe.config檔案中appSettings配置節增加一對鍵、值對
/// </summary>
/// <param name="newKey"></param>
/// <param name="newValue"></param>
private static void UpdateAppConfig(string newKey, string newValue)
{
bool isModified = false ;
foreach (string key in ConfigurationManager .AppSettings)
{
if (key==newKey)
{
isModified = true ;
}
}
// Open App.Config of executable
Configuration config =
ConfigurationManager .OpenExeConfiguration(ConfigurationUserLevel .None);
// You need to remove the old settings object before you can replace it
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
// Add an Application Setting.
config.AppSettings.Settings.Add(newKey,newValue);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode .Modified);
// Force a reload of a changed section.
ConfigurationManager .RefreshSection("appSettings" );
}
C#讀寫app.config中的資料
讀語句:
String str = ConfigurationManager.AppSettings["DemoKey"];
寫語句:
Configuration cfa =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue";
cfa.Save();
配置檔案內容格式:(app.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DemoKey" value="*" />
</appSettings>
</configuration>
紅筆標明的幾個關鍵節是必須的
System.Configuration.ConfigurationSettings.AppSettings["Key"];
但是現在FrameWork2.0已經明確表示此屬性已經過時。並建議改為ConfigurationManager
或WebConfigurationManager。並且AppSettings屬性是隻讀的,並不支援修改屬性值.
但是要想呼叫ConfigurationManager必須要先在工程裡新增system.configuration.dll程式集的引用。
(在解決方案管理器中右鍵點選工程名稱,在右鍵選單中選擇新增引用,.net TablePage下即可找到)
新增引用後可以用 String str = ConfigurationManager.AppSettings["Key"]來獲取對應的值了。
更新配置檔案:
Configuration cfa = ConfigurationManager.
OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings.Add("key", "Name") ||
cfa.AppSettings.Settings["BrowseDir"].Value = "name";
等等...
最後呼叫
cfa.Save();
當前的配置檔案更新成功。
*****************************************************************************************************************
讀寫配置檔案app.config
在.Net中提供了配置檔案,讓我們可以很方面的處理配置資訊,這個配置是XML格式的。而且.Net中已經提供了一些訪問這個檔案的功能。
1、讀取配置資訊
下面是一個配置檔案的具體內容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConnenctionString" value="*" />
<add key="TmpPath" value="C:\Temp" />
</appSettings>
</configuration>
.net提供了可以直接訪問<appsettings>(注意大小寫)元素的方法,在這元素中有很多的子元素,這些子元素名稱都是 “add”,有兩個屬性分別是“key”和“value”。一般情況下我們可以將自己的配置資訊寫在這個區域中,通過下面的方式進行訪問:
string ConString=System.Configuration
.ConfigurationSettings.AppSettings["ConnenctionString"];
在appsettings後面的是子元素的key屬性的值,例如appsettings["connenctionstring"],我們就是訪 問<add key="ConnenctionString" value="*" />這個子元素,它的返回值就是“*”,即value屬性的值。
2、設定配置資訊
如果配置資訊是靜態的,我們可以手工配置,要注意格式。如果配置資訊是動態的,就需要我們寫程式來實現。在.Net中沒有寫配置檔案的功能,我們可以使用操作XML檔案的方式來操作配置檔案。下面就是一個寫配置檔案的例子。
private void SaveConfig(string ConnenctionString)
{
XmlDocument doc=new XmlDocument();
//獲得配置檔案的全路徑
string strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()
+"Code.exe.config";
doc.LOAd(strFileName);
//找出名稱為“add”的所有元素
XmlNodeList nodes=doc.GetElementsByTagName("add");
for(int i=0;i<nodes.Count;i++)
{
//獲得將當前元素的key屬性
XmlAttribute att=nodes[i].Attributes["key"];
//根據元素的第一個屬性來判斷當前的元素是不是目標元素
if (att.Value=="ConnectionString")
{
//對目標元素中的第二個屬性賦值
att=nodes[i].Attributes["value"];
att.Value=ConnenctionString;
break;
}
}
//儲存上面的修改
doc.Save(strFileName);
}
讀取並修改App.config檔案
1. 向專案新增app.config檔案:
右擊專案名稱,選擇“新增”→“新增新建項”,在出現的“新增新項”對話方塊中,選擇“新增應用程式配置檔案”;如果專案以前沒有配置檔案,則預設的檔名稱為“app.config”,單擊“確定”。出現在設計器檢視中的app.config檔案為:
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
</configuration>
在專案進行編譯後,在bin\Debuge檔案下,將出現兩個配置檔案(以本專案為例),一個名為“JxcManagement.EXE.config”,另一個名為“JxcManagement.vshost.exe.config”。第一個檔案為專案實際使用的配置檔案,在程式執行中所做的更改都將被保存於此;第二個檔案為原始碼“app.config”的同步檔案,在程式執行中不會發生更改。
2. connectionStrings配置節:
請注意:如果您的SQL版本為2005 Express版,則預設安裝時SQL伺服器例項名為localhost\SQLExpress,須更改以下例項中“Data Source=localhost;”一句為“Data Source=localhost\SQLExpress;”,在等於號的兩邊不要加上空格。
<!--資料庫連線串-->
<connectionStrings>
<clear />
<addname="conJxcBook"
connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********"
providerName="System.Data.SqlClient" />
</connectionStrings>
3. appSettings配置節:
appSettings配置節為整個程式的配置,如果是對當前使用者的配置,請使用userSettings配置節,其格式與以下配置書寫要求一樣。
<!--進銷存管理系統初始化需要的引數-->
<appSettings>
<clear />
<addkey="userName"value="" />
<addkey="password"value="" />
<addkey="Department"value="" />
<addkey="returnValue"value="" />
<addkey="pwdPattern"value="" />
<addkey="userPattern"value="" />
</appSettings>
4.讀取與更新app.config
對於app.config檔案的讀寫,參照了網路文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題為“Read/Write App.Config File with .NET 2.0”一文。
請注意:要使用以下的程式碼訪問app.config檔案,除新增引用System.Configuration外,還必須在專案新增對System.Configuration.dll的引用。
4.1 讀取connectionStrings配置節
///<summary>
///依據連線串名字connectionName返回資料連線字串
///</summary>
///<param name="connectionName"></param>
///<returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =
ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
Console.WriteLine(connectionString);
return connectionString;
}
4.2 更新connectionStrings配置節
///<summary>
///更新連線字串
///</summary>
///<param name="newName">連線字串名稱</param>
///<param name="newConString">連線字串內容</param>
///<param name="newProviderName">資料提供程式名稱</param>
private static void UpdateConnectionStringsConfig(string newName,
string newConString,
string newProviderName)
{
bool isModified = false; //記錄該連線串是否已經存在
//如果要更改的連線串已經存在
if (ConfigurationManager.ConnectionStrings[newName] != null)
{
isModified = true;
}
//新建一個連線字串例項
ConnectionStringSettings mySettings =
new ConnectionStringSettings(newName, newConString, newProviderName);
// 開啟可執行的配置檔案*.exe.config
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 如果連線串已存在,首先刪除它
if (isModified)
{
config.ConnectionStrings.ConnectionStrings.Remove(newName);
}
// 將新的連線串新增到配置檔案中.
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
// 儲存對配置檔案所作的更改
config.Save(ConfigurationSaveMode.Modified);
// 強制重新載入配置檔案的ConnectionStrings配置節
ConfigurationManager.RefreshSection("ConnectionStrings");
}
4.3 讀取appStrings配置節
///<summary>
///返回*.exe.config檔案中appSettings配置節的value項
///</summary>
///<param name="strKey"></param>
///<returns></returns>
private static string GetAppConfig(string strKey)
{
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == strKey)
{
return ConfigurationManager.AppSettings[strKey];
}
}
return null;
}
4.4 更新connectionStrings配置節
///<summary>
///在*.exe.config檔案中appSettings配置節增加一對鍵、值對
///</summary>
///<param name="newKey"></param>
///<param name="newValue"></param>
private static void UpdateAppConfig(string newKey, string newValue)
{
bool isModified = false;
foreach (string key in ConfigurationManager.AppSettings)
{
if(key==newKey)
{
isModified = true;
}
}
// Open App.Config of executable
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// You need to remove the old settings object before you can replace it
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
// Add an Application Setting.
config.AppSettings.Settings.Add(newKey,newValue);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}
url:http://greatverve.cnblogs.com/archive/2011/07/18/app-config.html