【C#】ASP.NET Web.Config 读写辅助类
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
using System; using System.Configuration; using System.Web; using System.Web.Configuration; namespace Whir.ezEIP { /// ///
WebConfig读写辅助类 /// public class
WebConfigManager : IDisposable { private
Configuration _config; /// ///
WebConfig读写辅助类 /// public
WebConfigManager() :
this(HttpContext.Current.Request.ApplicationPath) { } /// ///
WebConfig读写辅助类 /// /// public
WebConfigManager(string path) {
_config = WebConfigurationManager.OpenWebConfiguration(path); } #region
IDisposable Members public
void Dispose() { if
(_config != null) {
_config.Save(); } }
#endregion /// /// 设置应用程序配置节点,如果已经存在此节点,则会修改该节点的值,否则添加此节点 /// /// 节点名称 /// 节点值 public
void SetAppSetting(string key, string value) { var
appSetting = (AppSettingsSection)_config.GetSection("appSettings"); if
(appSetting.Settings[key] == null) //如果不存在此节点,则添加
{ appSetting.Settings.Add(key, value); } else
//如果存在此节点,则修改 {
appSetting.Settings[key].Value = value; }
Save(); } /// /// 设置数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值,存在则修改 /// /// 节点名称 /// public
void SetConnectionString(string key, string connectionString) { var
connectionSetting =
(ConnectionStringsSection)_config.GetSection("connectionStrings"); if (connectionSetting.ConnectionStrings[key]
== null) //如果不存在此节点,则添加 {
var connectionStringSettings = new ConnectionStringSettings(key,
connectionString);
connectionSetting.ConnectionStrings.Add(connectionStringSettings); } else
//如果存在此节点,则修改 {
connectionSetting.ConnectionStrings[key].ConnectionString =
connectionString; }
Save(); } /// /// 保存所作的修改 /// public
void Save() {
_config.Save();
_config = null; } }
} 使用方法: var config = new WebConfigManager(); config.SetAppSetting("StrRegex", ""); 读取AppSetting和ConnectionString: string fileType=ConfigurationManager.AppSettings["FileType "]; string connectionString = ConfigurationManager.ConnectionStrings["AspNetStudyConnectionString1"].ConnectionString; 该文章在 2021/5/11 18:08:52 编辑过 |
关键字查询
相关文章
正在查询... |