C#使用log4net后简便的读取App.config方法

  • App.config添加节点appSettings,配置key-value信息
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net configSource="log4net.config" />
  <appSettings>
    <!--name-->
    <add key="name" value="xu"/>
    <!--value-->
    <add key="password" value="pw123456"/>
  </appSettings>
</configuration>
  • 新建类SystemConfig.cs,并引用using System.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using log4net;

namespace Demo_ConfigurationManager
{
    public static class SystemConfig
    {
        private static readonly ILog log = LogManager.GetLogger("Demo_ConfigurationManager");
        public static bool LoadSystemConfig()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string name = config.AppSettings.Settings["name"].Value;
            string password = config.AppSettings.Settings["password"].Value;
            log.Info("LoadSystemConfig success");
            return true;
        }

        public static bool SaveSystemConfig()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["name"].Value = "xujiangsu";
            config.AppSettings.Settings["password"].Value = "ce123";
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            log.Info("SaveSystemConfig success");
            return true;
        }
    }
}
  • 使用Configuration需要先引入log4net,否则找不到。使用config。AppSettings.Settings[key].Vlaue就可以读取配置信息了
posted @   小徐的小菜园  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示