C#读写config配置文件

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public static class ConfigHelper
{
public static LocalConfig _LocalConfig = null;
static ConfigHelper()
{
_LocalConfig = new LocalConfig();
}
}

public class ConfigBase
{
protected Configuration configObject;
public ConfigBase(string configFilePath)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = configFilePath;
configObject = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
}
protected void SetConfig(object value, [CallerMemberName] string key = null)
{
try
{
if (value == null)
value = string.Empty;
if (!configObject.AppSettings.Settings.AllKeys.Contains(key))
configObject.AppSettings.Settings.Add(key, value.ToString());
else
configObject.AppSettings.Settings[key].Value = value.ToString();
configObject.Save(ConfigurationSaveMode.Modified);
}
catch(Exception ex)
{
throw ex;
}
}
public object GetConfig([CallerMemberName] string key = null)
{
object value = string.Empty;
if (configObject.AppSettings.Settings.AllKeys.Contains(key))
{
value = configObject.AppSettings.Settings[key].Value;
}
return value;
}
}

public class LocalConfig : ConfigBase
{
static string filePath = AppDomain.CurrentDomain.BaseDirectory + "Static\\Config\\loc.config";
public LocalConfig():base(filePath) { }
public string LocalPath
{
get { return (string)GetConfig(); }
set { SetConfig(value); }
}
public bool Timestamp
{
get
{
object value = GetConfig();
if (string.IsNullOrEmpty(value.ToString()))
{
value = true;
SetConfig(value.ToString());
}
return Convert.ToBoolean(value);
}
set { SetConfig(value); }
}
}