【C#】ASP.NET Web.Config 讀寫輔助類
當前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
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 /// /// 設置應用程序配置節(jié)點,如果已經(jīng)存在此節(jié)點,則會修改該節(jié)點的值,否則添加此節(jié)點 /// /// 節(jié)點名稱 /// 節(jié)點值 public
void SetAppSetting(string key, string value) { var
appSetting = (AppSettingsSection)_config.GetSection("appSettings"); if
(appSetting.Settings[key] == null) //如果不存在此節(jié)點,則添加
{ appSetting.Settings.Add(key, value); } else
//如果存在此節(jié)點,則修改 {
appSetting.Settings[key].Value = value; }
Save(); } /// /// 設置數(shù)據(jù)庫連接字符串節(jié)點,如果不存在此節(jié)點,則會添加此節(jié)點及對應的值,存在則修改 /// /// 節(jié)點名稱 /// public
void SetConnectionString(string key, string connectionString) { var
connectionSetting =
(ConnectionStringsSection)_config.GetSection("connectionStrings"); if (connectionSetting.ConnectionStrings[key]
== null) //如果不存在此節(jié)點,則添加 {
var connectionStringSettings = new ConnectionStringSettings(key,
connectionString);
connectionSetting.ConnectionStrings.Add(connectionStringSettings); } else
//如果存在此節(jié)點,則修改 {
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 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |