讀配置很簡單,能夠用ConfigurationManager.AppSettings[key] 來讀出,app
但是寫配置文件時,若是寫成這樣ide
ConfigurationManager.AppSettings[key] = "111";spa
老是提示只讀,那麼該怎麼辦呢?調試
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Configuration;
-
- namespace BQKJ.Common
- {
-
-
-
-
- public class ConfigAppSettings
- {
-
-
-
-
-
- public static void SetValue(string key, string value)
- {
-
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- if (config.AppSettings.Settings[key] == null)
- {
- config.AppSettings.Settings.Add(key, value);
- }
- else
- {
- config.AppSettings.Settings[key].Value = value;
- }
- config.Save(ConfigurationSaveMode.Modified);
- ConfigurationManager.RefreshSection("appSettings");
- }
-
-
-
-
-
-
- public static string GetValue(string key)
- {
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- if (config.AppSettings.Settings[key] == null)
- return "";
- else
- return config.AppSettings.Settings[key].Value;
- }
-
- }
- }
其實也很簡單,用這兩個封裝過的方法就能夠了。server
須要注意的是,在IDE調試時,寫入的配置文件實際上是寫在了.vshost.exe.config文件中,因此你在.exe.config中是看不到的。只有直接運行exe文件時,纔會正確寫入到.exe.config中。ci
private void button1_Click(object sender, EventArgs e)string
{it
string serverIP = ConfigHelper.GetValue("ServerIP");io
string db = ConfigHelper.GetValue("DataBase");class
string user = ConfigHelper.GetValue("user");
string password = ConfigHelper.GetValue("password");
string info = "serverIP:" + serverIP + "\r\n"
+ "db:" + db + "\r\n"
+ "user:" + user + "\r\n"
+ "password:" + password + "\r\n";
MessageBox.Show(info);
ConfigHelper.SetValue("DataBase", "ttdb");
string newIP = ConfigHelper.GetValue("DataBase");
MessageBox.Show(newIP);
}
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Configuration;
-
- namespace BQKJ.Common
- {
-
-
-
-
- public class ConfigAppSettings
- {
-
-
-
-
-
- public static void SetValue(string key, string value)
- {
-
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- if (config.AppSettings.Settings[key] == null)
- {
- config.AppSettings.Settings.Add(key, value);
- }
- else
- {
- config.AppSettings.Settings[key].Value = value;
- }
- config.Save(ConfigurationSaveMode.Modified);
- ConfigurationManager.RefreshSection("appSettings");
- }
-
-
-
-
-
-
- public static string GetValue(string key)
- {
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- if (config.AppSettings.Settings[key] == null)
- return "";
- else
- return config.AppSettings.Settings[key].Value;
- }
-
- }
- }