在Winform中動態讀寫app.config文件 https://blog.csdn.net/kingmax54212008/article/details/38987277?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.n ...
在Winform中動態讀寫app.config文件
https://blog.csdn.net/kingmax54212008/article/details/38987277?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-38987277-blog-82746084.235%5Ev36%5Epc_relevant_default_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-38987277-blog-82746084.235%5Ev36%5Epc_relevant_default_base3&utm_relevant_index=12
1、 首先需要在項目中引用:System.Configuration
2、 通過OpenExeConfiguration()這個方法來對配置文件進行操作
若當前項目的配置文件如下:
- <configuration>
- <appSettings>
- <clear />
- <add key="DataSource" value=".\SQL2005"/>
- <!-- 資料庫服務地址-->
- <add key="InitialCatalog" value="db"/>
- <!-- 資料庫名稱-->
- <add key="UserId" value="sa"/>
- <!-- 用戶名-->
- <add key="Password" value="sa"/>
- <!-- 這個密碼是加密之後的-->
- <add key="ConnectTimeout" value="1000"/>
- </appSettings>
- <startup>
- <supportedRuntime version="v2.0.50727"/>
- </startup>
- </configuration>
需要對上面appSettings的鍵值作修改,如下代碼所示:
- string path = Application.StartupPath + "\\ASSEMLY.exe";
- Configuration config = ConfigurationManager.OpenExeConfiguration(path);
- config.AppSettings.Settings.Clear();
- config.AppSettings.Settings.Add("DataSource", this.DataSource);
- config.AppSettings.Settings.Add("InitialCatalog", this.InitialCatalog);
- config.AppSettings.Settings.Add("UserId", this.UserId);
- config.AppSettings.Settings.Add("Password", this.DePassword);
- config.AppSettings.Settings.Add("ConnectTimeout", this.ConnectTimeout.ToString());
- // 保存對配置文件所作的更改
- config.Save(ConfigurationSaveMode.Modified);
- // 強制重新載入配置文件的ConnectionStrings配置節
- ConfigurationManager.RefreshSection("appSettings");
其中它是不能直接修改健值的,是在修改之前要刪除該鍵值,然後重新添加
同是,上面的只是對AppSettings進行操作,其實也可以對ConnectionStrings、SectionGroups、Sections進行操作
讀取所有的AppSettings的值
StringBuilder str = new StringBuilder();
str.Append("<table class='isTable'><tr><th></th><th>用戶名</th><th>webservices地址</th><th>webservices方法名稱</th></tr>");
AppSettingsReader reader =
new AppSettingsReader();
NameValueCollection appStgs =
ConfigurationManager.AppSettings;
string[] names =
ConfigurationManager.AppSettings.AllKeys;
String value = String.Empty;
for (int i = 0; i < appStgs.Count; i++)
{
string key = names[i];
if (key.IndexOf("WebSiteUser") >= 0)
{
value = (String)reader.GetValue(key, value.GetType());
string[] strValue = value.Split(',');
string webservices = strValue[0];
string method = strValue[1];
str.Append("<tr><td><a style='color:White;text-decoration: none;' href=\"/sdmin/EditWebSiteUser?key=" + key + "\"><img src='../../Content/icons/admin_edit.png' alt='' title='編輯'/></a></td><td>" + key.Replace("WebSiteUser", "") + "</td><td>" + webservices + "</td><td>" + method + "</td></tr>");
}
}
str.Append("</table>");
ViewData["ListWebSiteUser"] = str;
return View();
現在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager。並且AppSettings屬性是只讀的,並不支持修改屬性值.
一、如何使用ConfigurationManager?
1、添加引用:添加System.configguration
2、引用空間
3、config配置文件配置節
常用配置節:
(1)普通配置節
<appSettings>
<add key="COM1" value="COM1,9600,8,None,1,已啟用" />
</appSettings>
(2)數據源配置節
<connectionStrings>
<add name="kyd" connectionString="server=.;database=UFDATA_999_2017;user=sa;pwd=123"/>
</connectionStrings>
(3)自定義配置節
二、config文件讀寫
1、依據連接串名字connectionName返回數據連接字元串
//依據連接串名字connectionName返回數據連接字元串 public static string GetConnectionStringsConfig(string connectionName) { //指定config文件讀取 string file = System.Windows.Forms.Application.ExecutablePath; System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file); string connectionString = config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString(); return connectionString; }
2、更新連接字元串
///<summary> ///更新連接字元串 ///</summary> ///<param name="newName">連接字元串名稱</param> ///<param name="newConString">連接字元串內容</param> ///<param name="newProviderName">數據提供程式名稱</param> public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName) { //指定config文件讀取 string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); bool exist = false; //記錄該連接串是否已經存在 //如果要更改的連接串已經存在 if (config.ConnectionStrings.ConnectionStrings[newName] != null) { exist = true; } // 如果連接串已存在,首先刪除它 if (exist) { config.ConnectionStrings.ConnectionStrings.Remove(newName); } //新建一個連接字元串實例 ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName); // 將新的連接串添加到配置文件中. config.ConnectionStrings.ConnectionStrings.Add(mySettings); // 保存對配置文件所作的更改 config.Save(ConfigurationSaveMode.Modified); // 強制重新載入配置文件的ConnectionStrings配置節 ConfigurationManager.RefreshSection("connectionStrings"); }
3、返回*.exe.config文件中appSettings配置節的value項
///<summary> ///返回*.exe.config文件中appSettings配置節的value項 ///</summary> ///<param name="strKey"></param> ///<returns></returns> public static string GetAppConfig(string strKey) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == strKey) { return config.AppSettings.Settings[strKey].Value.ToString(); } } return null; }
4、在*.exe.config文件中appSettings配置節增加一對鍵值對
///<summary> ///在*.exe.config文件中appSettings配置節增加一對鍵值對 ///</summary> ///<param name="newKey"></param> ///<param name="newValue"></param> public static void UpdateAppConfig(string newKey, string newValue) { 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 == newKey) { exist = true; } } if (exist) { config.AppSettings.Settings.Remove(newKey); } config.AppSettings.Settings.Add(newKey, newValue); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); }
5、修改IP地址
// 修改system.serviceModel下所有服務終結點的IP地址 public static void UpdateServiceModelConfig(string configPath, string serverIP) { Configuration config = ConfigurationManager.OpenExeConfiguration(configPath); ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"]; ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup; ClientSection clientSection = serviceModelSectionGroup.Client; foreach (ChannelEndpointElement item in clientSection.Endpoints) { string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; string address = item.Address.ToString(); string replacement = string.Format("{0}", serverIP); address = Regex.Replace(address, pattern, replacement); item.Address = new Uri(address); } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("system.serviceModel"); } // 修改applicationSettings中App.Properties.Settings中服務的IP地址 public static void UpdateConfig(string configPath, string serverIP) { Configuration config = ConfigurationManager.OpenExeConfiguration(configPath); ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"]; ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"]; ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection; if (clientSettingsSection != null) { SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS"); if (element1 != null) { clientSettingsSection.Settings.Remove(element1); string oldValue = element1.Value.ValueXml.InnerXml; element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP); clientSettingsSection.Settings.Add(element1); } SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS"); if (element2 != null) { clientSettingsSection.Settings.Remove(element2); string oldValue = element2.Value.ValueXml.InnerXml; element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP); clientSettingsSection.Settings.Add(element2); } } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("applicationSettings"); } private static string GetNewIP(string oldValue, string serverIP) { string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; string replacement = string.Format("{0}", serverIP); string newvalue = Regex.Replace(oldValue, pattern, replacement); return newvalue; }
修改IP地址
config 讀寫方法
using System.Configuration; //省略其他代碼 public SalesOrderData() { string str = ""; str = ConfigurationManager.ConnectionStrings["kyd"].ToString(); conn = new SqlConnection(str); cmd = conn.CreateCommand(); }
實際應用:
1、獲取配置節的值
button1 點擊獲取配置節<appSettings>指定key的value值
button2 點擊獲取配置節<connectionStrings>指定name的connectionString值
結果為:
2、修改配置節的值
button1 點擊獲取配置節<appSettings>指定key的value值
button2 點擊修改配置節<connectionStrings>指定key的value值為文本框的值
button3 點擊獲取配置節<appSettings>指定key新的value值
結果為:
此時配置文件key1的value值為,獲取key值仍為修改前的值
如何重置為修改前的值?
如何保存修改後的值?