zhaolei
2020-11-20 4a2e5b9a21940f11757be37d99f0944e240e908b
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
#if NET45
using System;
using System.Configuration;
 
namespace Prow.Configuration
{
    /// <summary>
    /// 配置文件保存扩展类
    /// </summary>
    public static class LgbConfigurationManager
    {
        /// <summary>
        /// 更新指定AppSettings小节的KeyValue对,并不保存配置文件
        /// </summary>
        /// <param name="appSection"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void UpdateAppSettings(AppSettingsSection appSection, string key, string value)
        {
            if (appSection == null) throw new ArgumentNullException("appSection");
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
 
            if (appSection.Settings[key] == null)
                appSection.Settings.Add(key, value);
            else
                appSection.Settings[key].Value = value;
        }
 
        /// <summary>
        /// 保存AppSettings到配置文件中
        /// </summary>
        /// <param name="config"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SaveAppSettings(System.Configuration.Configuration config, string key, string value)
        {
            if (config == null) throw new ArgumentNullException("config");
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
            var section = config.AppSettings;
            if (section == null)
            {
                section = new AppSettingsSection();
                config.Sections.Add(section.SectionInformation.Name, section);
            }
            UpdateAppSettings(section, key, value);
            config.Save(ConfigurationSaveMode.Minimal);
        }
    }
}
#endif