文章分类

相关文章

ASP.NET 读写Webconfig的AppSetting和ConnectionString

分类:ASP.NET     发布:2018-09-27     来源:本站     浏览:155 次
using System.Configuration;
using System.Web;
using System.Web.Configuration;

namespace RC.Website.Webservice.Controllers
{
    /// <summary>
    ///     ASP.NET 配置文件写辅助类
    /// </summary>
    public class ConfigurationHelper
    {
        /// <summary>
        ///     读取链接字符串
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetConnectionString(string key = "")
        {
            var setting = ConfigurationManager.ConnectionStrings;
            if (key.Length == 0 && setting.Count > 0) return setting[0].ConnectionString;
            return setting[key] == null ? string.Empty : setting[key].ConnectionString;
        }

        /// <summary>
        ///     设置数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值;存在则修改
        /// </summary>
        /// <param name="key"></param>
        /// <param name="connectionString"></param>
        public void SetConnectionString(string key, string connectionString)
        {
            var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            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;
            }

            config.Save();
        }

        #region AppSetting读写

        /// <summary>
        ///     设置应用程序配置节点,如果已经存在此节点,则会修改该节点的值;否则添加此节点
        /// </summary>
        /// <param name="key">节点名称</param>
        /// <param name="value">节点值</param>
        public void SetAppSetting(string key, string value)
        {
            var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            var appSetting = (AppSettingsSection) config.GetSection("appSettings");
            if (appSetting.Settings[key] == null)
                appSetting.Settings.Add(key, value);
            else
                appSetting.Settings[key].Value = value;

            config.Save();
        }

        /// <summary>
        ///     读取节点值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetAppSetting(string key)
        {
            return ConfigurationManager.AppSettings[key] ?? string.Empty;
        }

        #endregion
    }
}

上一篇:C# Winform异步操作

下一篇:C#文件读写辅助类(FileHelper)