两种读写配置文件的方案(app.config与web.config通用)

  1. 云栖社区>
  2. 博客>
  3. 正文

两种读写配置文件的方案(app.config与web.config通用)

技术小牛人 2017-11-15 19:19:00 浏览1097
展开阅读全文

第一种方法:采用MS现有的ConfigurationManager来进行读写

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System.Configuration;
 
 
namespace Zwj.TEMS.Common
{
    public abstract class ConfigHelper
    {
        private ConfigHelper()
        { }
 
        /// <summary>
        /// 获取配置值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppSettingValue(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
 
        /// <summary>
        /// 设置配置值(存在则更新,不存在则新增)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetAppSettingValue(string key, string value)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var setting = config.AppSettings.Settings[key];
            if (setting==null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                setting.Value = value;
            }
 
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
 
        /// <summary>
        /// 删除配置值
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveAppSetting(string key)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Remove(key);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
 
 
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetConnectionString(string name)
        {
          return  ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }
 
        /// <summary>
        /// 设置连接字符串的值(存在则更新,不存在则新增)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="connstr"></param>
        /// <param name="provider"></param>
        public static void SetConnectionString(string name,string connstr, string provider)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConnectionStringSettings connStrSettings = config.ConnectionStrings.ConnectionStrings[name];
            if (connStrSettings != null)
            {
                connStrSettings.ConnectionString = connstr;
                connStrSettings.ProviderName = provider;
            }
            else
            {
                connStrSettings = new ConnectionStringSettings(name, connstr, provider);
                config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
            }
 
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
 
        /// <summary>
        /// 删除连接字符串配置项
        /// </summary>
        /// <param name="name"></param>
        public static void RemoveConnectionString(string name)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove(name);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }
 
    }
}

 注意:不能直接使用ConfigurationManager.AppSettings及ConfigurationManager.ConnectionStrings进行写操作(即:Add,Remove),因为这两个属性是只读的,本人之前也疑惑,明明能够调用Add,Remove方法,但使用时却报错。

第二种方法:采用原生的XML+XPATH来读写(来源于网络)

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//==============================================
// FileName: ConfigManager
// Description: 静态方法业务类,用于对C#、ASP.NET中的WinForm & WebForm 项目程序配置文件
// app.config和web.config的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作。
//==============================================
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Xml;
 
public enum ConfigurationFile
{
    AppConfig = 1,
    WebConfig = 2
}
/// <summary>
/// ConfigManager 应用程序配置文件管理器
/// </summary>
public class ConfigManager
{
    public ConfigManager()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
 
    /// <summary>
    /// 对[appSettings]节点依据Key值读取到Value值,返回字符串
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">要读取的Key值</param>
    /// <returns>返回Value值的字符串</returns>
    public static string ReadValueByKey(ConfigurationFile configurationFile, string key)
    {
        string value = string.Empty;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }
 
        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
        ////得到[appSettings]节点中关于Key的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
        if (element != null)
        {
            value = element.GetAttribute("value");
        }
        return value;
    }
    /// <summary>
    /// 对[connectionStrings]节点依据name值读取到connectionString值,返回字符串
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="name">要读取的name值</param>
    /// <returns>返回connectionString值的字符串</returns>
    public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name)
    {
        string connectionString = string.Empty;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[appSettings]节点
        ////得到[connectionString]节点中关于name的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
        if (element != null)
        {
            connectionString = element.GetAttribute("connectionString");
        }
        return connectionString;
    }
    /// <summary>
    /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">子节点Key值</param>
    /// <param name="value">子节点value值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
        try
        {
            ////得到[appSettings]节点中关于Key的子节点
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
            if (element != null)
            {
                //存在则更新子节点Value
                element.SetAttribute("value", value);
            }
            else
            {
                //不存在则新增子节点
                XmlElement subElement = doc.CreateElement("add");
                subElement.SetAttribute("key", key);
                subElement.SetAttribute("value", value);
                node.AppendChild(subElement);
            }
            //保存至配置文件(方式一)
            using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
            {
                xmlwriter.Formatting = Formatting.Indented;
                doc.WriteTo(xmlwriter);
                xmlwriter.Flush();
            }
            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
            throw ex;
        }
        return isSuccess;
    }
    /// <summary>
    /// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="name">子节点name值</param>
    /// <param name="connectionString">子节点connectionString值</param>
    /// <param name="providerName">子节点providerName值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点
        try
        {
            ////得到[connectionStrings]节点中关于Name的子节点
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
            if (element != null)
            {
                //存在则更新子节点
                element.SetAttribute("connectionString", connectionString);
                element.SetAttribute("providerName", providerName);
            }
            else
            {
                //不存在则新增子节点
                XmlElement subElement = doc.CreateElement("add");
                subElement.SetAttribute("name", name);
                subElement.SetAttribute("connectionString", connectionString);
                subElement.SetAttribute("providerName", providerName);
                node.AppendChild(subElement);
            }
            //保存至配置文件(方式二)
            doc.Save(filename);
            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
            throw ex;
        }
        return isSuccess;
    }
    /// <summary>
    /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="key">要删除的子节点Key值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool DeleteByKey(ConfigurationFile configurationFile, string key)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
        ////得到[appSettings]节点中关于Key的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
        if (element != null)
        {
            //存在则删除子节点
            element.ParentNode.RemoveChild(element);
        }
        else
        {
            //不存在
        }
        try
        {
            //保存至配置文件(方式一)
            using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
            {
                xmlwriter.Formatting = Formatting.Indented;
                doc.WriteTo(xmlwriter);
                xmlwriter.Flush();
            }
            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
        }
        return isSuccess;
    }
    /// <summary>
    /// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
    /// </summary>
    /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
    /// <param name="name">要删除的子节点name值</param>
    /// <returns>返回成功与否布尔值</returns>
    public static bool DeleteByName(ConfigurationFile configurationFile, string name)
    {
        bool isSuccess = false;
        string filename = string.Empty;
        if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
        {
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
        }
        else
        {
            filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(filename); //加载配置文件
        XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点
        ////得到[connectionStrings]节点中关于Name的子节点
        XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
        if (element != null)
        {
            //存在则删除子节点
            node.RemoveChild(element);
        }
        else
        {
            //不存在
        }
        try
        {
            //保存至配置文件(方式二)
            doc.Save(filename);
            isSuccess = true;
        }
        catch (Exception ex)
        {
            isSuccess = false;
        }
        return isSuccess;
    }
}

更多IT相关技术文章与资讯,欢迎光临我的个人网站:http://www.zuowenjun.cn

本文转自 梦在旅途 博客园博客,原文链接:http://www.cnblogs.com/zuowj/p/4398841.html  ,如需转载请自行联系原作者

网友评论

登录后评论
0/500
评论
技术小牛人
+ 关注