標籤:color io 使用 ar for strong 檔案 sp div
設定檔在很多情況下都使用到, 設定檔分為兩種 一種是應用程式的設定檔, 一種是web的設定檔.
兩種設定檔最大的區別是web的設定檔更新之後會即時更新, 應用程式的設定檔不會即時更新.
更新應用程式的設定檔之後需重新整理
ConfigurationManager.RefreshSection("appSettings");// 重新整理命名節,在下次檢索它時將從磁碟重新讀取它。
ConfigurationSettings也存在這個問題, 但是我還不知道怎麼重新整理節點, 呵呵.
舊方法: 各位看官最好使用下面”新方法”
設定檔:
<configuration>
<appSettings>
<add key="name" value="我是遠程伺服器"/>
</appSettings>
</configuration>
背景程式值得讀取:
string s=System.Configuration.ConfigurationSettings.AppSettings["name"];
修改設定檔的值:
| 1234567891011121314 |
/// <summary>/// 更新設定檔資訊/// </summary>/// <param name="name">設定檔欄位名稱</param>/// <param name="Xvalue">值</param>private void UpdateConfig(string name,string Xvalue){ XmlDocument doc = new XmlDocument(); doc.Load(Application.ExecutablePath + ".config"); XmlNode node = doc.SelectSingleNode(@"//add[@key=‘"+name+"‘]"); XmlElement ele = (XmlElement)node; ele.SetAttribute("value", Xvalue); doc.Save(Application.ExecutablePath + ".config");} |
向設定檔插入值:
| 12345678910111213141516171819202122232425 |
///<summary> ///向.config檔案的appKey結寫入資訊AppValue 儲存設定 ///</summary> ///<param name="AppKey">節點名</param> ///<param name="AppValue">值</param>Private void SetValue(String AppKey,String AppValue){ Xmldocument xDoc=new XmlDocument(); xDoc.Load(System.Windows.Forms.Application.ExecutablePath+”.config”); XmlNode xNode; XmlElement xElem1; XmlElement xElem2; xNode=xDoc.SelectSingleNode(“//appSettings”); xElem1=(XmlElement)xNode.SelectSingleNode(“//add[@key=’”+AppKey+”’]”); if(xElem1!=null) xElem1.SetAttribute(“value”,AppValue); else { xElem2=xdoc.CreateElement(“add”); xElem2.SetAttribute(“key”,AppKey); xElem2.setAttribute(“value”,AppValue); xNode.AppendChild(xElem2); } xDoc.Save(System.Windows.Forms.Application.ExecutablePath+”.config”);} |
新方法:
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();
當前的設定檔更新成功。
ConfigurationManager.RefreshSection("appSettings");// 重新整理命名節,在下次檢索它時將從磁碟重新讀取它。記住應用程式要重新整理節點
C# 設定檔讀取與修改