添加引用 using System.Configuration;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Config
{
//没弄明白appSettings和connectionStrings除了在配置文件中节点不同以外还有什么区别,我更倾向于使用appSettings

static public void Write(string key,string value)
{
bool Exist = false;
var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
foreach (string s in conf.AppSettings.Settings.AllKeys)
{
if (s == key)
{
conf.AppSettings.Settings[s].Value = value;
Exist = true;
}
}
if (!Exist)
{
conf.AppSettings.Settings.Add(key, value);
}
conf.Save();
ConfigurationManager.RefreshSection("appSettings");
}

static public string Read(string key)
{
ConfigurationManager.RefreshSection("appSettings");
var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
return conf.AppSettings.Settings[key].Value ?? "";
}

static public void Remove(string key)
{
var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
conf.AppSettings.Settings.Remove(key);
ConfigurationManager.RefreshSection("appSettings");
}
}