读配置很简单,能够用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;
- }
-
- }
- }