若需要修改則可以打開配置文件,操作節點屬性。App.config 配置文件是項目自帶的xml文件, 可以使用 .net自帶的類ConfigurationManager去訪問,但首先需要引入System.Configuration 類庫。在該配置文件中,常用的配置節點有3種:
1. 數據庫連接字符串節點 connectionStrings
<connectionStrings> <add name="HolipERP" connectionString="Server=cnhay01as02;User ID=hlpsfs;Password=8nasalt;Database=sfsData;" providerName="SQLOLEDB.1"/> <add name="TestData" connectionString="Server=cnhay01as01;User ID=production;Password=holipserver;Database=Test_Memo_Data;" providerName="SQLOLEDB.1" /> </connectionStrings>
可用 ConfigurationManager.ConnectionStrings[name].ToString() 讀取connectionString屬性 ,好像找不到直接修改的方法,我是采用先刪除再添加的方式修改的,其實一般也不會在程序里面動態修改這個配置字節。
2. 系統參數配置 AppSettings
<appSettings> <add key="PLC_IP" value="192.168.0.11" /> </appSettings>
這種配置是以鍵值對的方式存在的,可用 ConfigurationManager.AppSettings[key].ToString() 讀取 value 值, 若需要修改則可以打開配置文件,操作節點屬性。
Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //打開 vshost.exe.config appConfig.AppSettings.Settings.Add(key, value); appConfig.AppSettings.Settings.Remove(key); appConfig.AppSettings.Settings[key].Value = value;
3. 自定義配置 configSections
常用的有3種類型: System.Configuration.SingleTagSectionHandler (屬性值的方式)
System.Configuration.DictionarySectionHandler (鍵值對的方式)
System.Configuration. NameValueSectionHandler (鍵值對的方式)
可以加上分組標簽,另外有點很重要,configSections配置節必須放在開頭即configuration的第一個子元素,具體配置格式如下,
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="PLCData"> <section name="serialNum" type="System.Configuration.SingleTagSectionHandler"/> <section name="enableAssemble" type="System.Configuration.SingleTagSectionHandler"/> </sectionGroup> <section name="example1" type="System.Configuration.NameValueSectionHandler "/> </configSections> <PLCData> <serialNum DB="2" StartAddr="0" ByteLength="18" /> <enableAssemble DB="2" StartAddr="18" ByteLength="2" /> </PLCData> <example1> <add key="Hello" value="World" /> <add key="Good" value="Morning" /> </example1> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <connectionStrings> <add name="HolipERP" connectionString="Server=cnhay01as02;User ID=hlpsfs;Password=8nasalt;Database=sfsData;" providerName="SQLOLEDB.1"/> <add name="TestData" connectionString="Server=cnhay01as01;User ID=production;Password=holipserver;Database=Test_Memo_Data;" providerName="SQLOLEDB.1" /> </connectionStrings> <appSettings> <add key="PLC_IP" value="192.168.0.11" /> </appSettings> </configuration>
可通過 IDictionary IDic = (IDictionary)ConfigurationManager.GetSection(setionGroupName+"/"+setionName) 讀取配置,以鍵值對的方式保存。若需要修改,可采用xPath方式直接訪問。下面這個AppConfigManagement靜態類,當中的修改方法都是同時更新保存兩個配置文件的,原因注釋里有寫到。
/// <summary> /// winform會自動生成有2個配置文件 vshost.exe.config 和 exe.config, 修改操作必須同時修改2個文件並同時保存, 如果只修改vshost.exe.config,程序重啟會重新讀取exe.config將其覆蓋 /// </summary> public static class AppConfigManagement { private static Configuration appConfig = null; // vshost.exe.config private static Configuration appConfig_original = null; // exe.config private static XmlDocument doc = null; //加載 vshost.exe.config static AppConfigManagement() { appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //打開 vshost.exe.config appConfig_original = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location); //打開 exe.config doc = new XmlDocument(); //加載 vshost.exe.config doc.Load(appConfig.FilePath); } //讀取連接字符串 public static string GetConnectionStringSet(string name) { try { return ConfigurationManager.ConnectionStrings[name].ToString(); }catch(Exception err){ throw new Exception("GetConnectionStringSet:" + err.Message); } } //修改連接字符串 public static void SetConnectionStringSet(string name,string value) { try { appConfig.ConnectionStrings.ConnectionStrings.Remove(name); //沒有直接修改的方法,只能先刪除,再創建 vshost.exe.config appConfig_original.ConnectionStrings.ConnectionStrings.Remove(name); // .exe.config appConfig.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, value)); //添加vshost.exe.config appConfig_original.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, value)); //添加exe.config appConfig.Save(); //保存vshost.exe.config appConfig_original.Save(); //保存exe.config ConfigurationManager.RefreshSection("connectionStrings"); //刷新內存中的配置值 if (!(GetConnectionStringSet(name) == value)) { //讀取比較確認修改成功 throw new Exception("Failed to SetConnectionStringSet"); } } catch (Exception err) { throw new Exception("SetConnectionStringSet:" + err.Message); } } //讀取程序配置 public static string GetAppSeting(string name) { try { return ConfigurationManager.AppSettings[name].ToString(); } catch (Exception err) { throw new Exception("GetAppSeting:" + err.Message); } } //添加程序配置 public static void AddAppSeting(string key,string value) { try { appConfig.AppSettings.Settings.Add(key, value); appConfig_original.AppSettings.Settings.Add(key, value); appConfig.Save(); //保存 appConfig_original.Save(); //保存 ConfigurationManager.RefreshSection("appSettings"); if (!(GetAppSeting(key) == value)) { //讀取比較確認添加成功 throw new Exception("Failed to AddAppSeting"); } } catch (Exception err) { throw new Exception("AddAppSeting:" + err.Message); } } //刪除程序配置 public static void DeleteAppSeting(string key) { try { appConfig.AppSettings.Settings.Remove(key); appConfig_original.AppSettings.Settings.Remove(key); appConfig.Save(); //保存 appConfig_original.Save(); //保存 ConfigurationManager.RefreshSection("appSettings"); } catch (Exception err) { throw new Exception("DeleteAppSeting:" + err.Message); } } //修改程序配置 public static void UpdateAppSeting(string key,string value) { try { appConfig.AppSettings.Settings[key].Value = value; appConfig_original.AppSettings.Settings[key].Value = value; appConfig.Save(); //保存 appConfig_original.Save(); //保存 ConfigurationManager.RefreshSection("appSettings"); if (!(GetAppSeting(key) == value)) { //讀取比較確認添加成功 throw new Exception("Failed to UpdateAppSeting"); } } catch (Exception err) { throw new Exception("UpdateAppSeting:" + err.Message); } } //讀取自定義配置節 //讀取System.Configuration.SingleTagSectionHandler類型,System.Configuration.NameValueSectionHandler類型和System.Configuration.DictionarySectionHandler類型自定義配置節 public static Dictionary<string, string> GetCustomizedSection(string setionName) { try { IDictionary IDic = (IDictionary)ConfigurationManager.GetSection(setionName); Dictionary<string,string> Dic_Copy = new Dictionary<string,string>(); foreach(object key in IDic.Keys){ Dic_Copy.Add(key.ToString(),IDic[key].ToString()); } return Dic_Copy; } catch (Exception err) { throw new Exception("GetCustomizedSection:" + err.Message); } } //讀取分組的System.Configuration.SingleTagSectionHandler類型,System.Configuration.NameValueSectionHandler類型和System.Configuration.DictionarySectionHandler類型自定義配置節 public static Dictionary<string, string> GetCustomizedSection(string setionGroupName,string setionName) { try { IDictionary IDic = (IDictionary)ConfigurationManager.GetSection(setionGroupName+"/"+setionName); Dictionary<string, string> Dic_Copy = new Dictionary<string, string>(); foreach (object key in IDic.Keys) { Dic_Copy.Add(key.ToString(), IDic[key].ToString()); } return Dic_Copy; } catch (Exception err) { throw new Exception("GetCustomizedSection:" + err.Message); } } //修改System.Configuration.SingleTagSectionHandler類型自定義配置節 public static void SetCustomizedSectionProperty(string setionGroup,string setionName, string propertyName, string value) { try { string xpath = ""; if (string.IsNullOrEmpty(setionGroup)) //是否有組 { xpath = setionName; } else { xpath = setionGroup + "/" + setionName; } XmlNode node = doc.SelectSingleNode(@"/configuration/"+xpath); //使用xPath的方式直接訪問 node.Attributes[propertyName].Value = value; //設置屬性值 doc.Save(appConfig.FilePath); //保存至 vshost.exe.config doc.Save(appConfig_original.FilePath); //保存至 exe.config ConfigurationManager.RefreshSection(xpath); //刷新內存中的配置值 } catch (Exception err) { throw new Exception("SetSingleTagSectionValue:" + err.Message); } } }