配置文件相关的代码

1、配置文件监听

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;

namespace CSharpStudy
{
    public sealed class ConfigMonitor
    {
        /// <summary>
        /// file path
        /// </summary>
        private static string filePath = string.Empty;

        /// <summary>
        /// file map
        /// </summary>
        private static ExeConfigurationFileMap configFileMap;

        /// <summary>
        /// constructor 
        /// </summary>
        static ConfigMonitor()
        {
            Console.WriteLine("constructor...");
            MonitorConfigFile();
            InitConfigInfo();
        }

        /// <summary>
        /// after change config delegate
        /// </summary>
        public delegate void AfterConfigModifyEvent();

        /// <summary>
        /// after change config event
        /// </summary>
        public static event AfterConfigModifyEvent afterConfigModifyEvent;

        /// <summary>
        /// config object
        /// </summary>
        public static Configuration Config
        {
            get;
            set;
        }

        /// <summary>
        /// monitor config file
        /// </summary>
        public static void MonitorConfigFile()
        {
            Console.WriteLine("MonitorConfigFile...");
            // don't throw exception 
            try
            {
                FileSystemWatcher fileWatcher = new FileSystemWatcher();
                fileWatcher.Path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                fileWatcher.Filter = "ParamSettings.config";

                // add event handlers
                fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
                fileWatcher.Created += new FileSystemEventHandler(OnChanged);
                fileWatcher.Deleted += new FileSystemEventHandler(OnChanged);
                fileWatcher.Renamed += new RenamedEventHandler(OnChanged);

                fileWatcher.EnableRaisingEvents = true;
            }
            catch
            {
            }
        }

        public static void OnChanged(object source, FileSystemEventArgs e)
        {
            InitConfigInfo();
            RaiseEvent();
        }

        /// <summary>
        /// init all config info
        /// </summary>
        public static void InitConfigInfo()
        {
            Console.WriteLine("InitConfigInfo...");

            try
            {
                // don't throw exception
                filePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\ParamSettings.config";
                configFileMap = new ExeConfigurationFileMap();
                configFileMap.ExeConfigFilename = filePath;
                Config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
            }
            catch
            {
            }
        }

        /// <summary>
        /// raise event 
        /// </summary>
        private static void RaiseEvent()
        {
            Console.WriteLine("RaiseEvent...");

            if (afterConfigModifyEvent != null)
            {
                afterConfigModifyEvent();
            }
        }
    }
}
复制代码

2、SettingsFactory

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpStudy
{
    public class SettingsFactory
    {
        static SettingsFactory()
        {
            ConfigMonitor.MonitorConfigFile();
        }

        public static string ApplicationName
        {
            get
            {
                return GetAppSetting("ApplicationName");
            }
        }


        private static string GetAppSetting(string key)
        {
            return ConfigMonitor.Config.AppSettings.Settings[key].Value;
        }
    }
}
复制代码

3、测试代码

复制代码
     public static void TestConfigFile()
        {
            while (true)
            {
                string str = Console.ReadLine();
                if (str == "-1")
                {
                    break;
                }

                Console.WriteLine(SettingsFactory.ApplicationName);
            }
        }
复制代码

4、运行截图

4.1 初始化

说明:

  在输入回车后,打印SettingsFactory.ApplicationName信息,

  第一、SettingsFactory构造函数初始化

  (1)、ConfigMonitor构造函数初始化,执行构造函数里面的方法

    打印:

    contructor...

    MonitorConfigFile...

      InitConfigInfo...

  (2)、执行ConfigMonitor.MonitorConfigFile方法

    打印:MonitorConfigFile...

    第二、执行SettingsFactory.ApplicationName方法,打印:CSharpStudy

4.2 使用值

  

  说明:再输入一次回车,结果打印:CSharpStudy。静态构造器,只在第一次使用该类的时候进行初始化。

4.3 程序运行时修改配置文件

找到项目所在目录下的:bin\Debug\ParamSettings.config配置文件,

将ApplicationName的Value修改为:测试项目

 

执行了四次OnChanged方法。

输入回车后

 

 5、配置文件ParamSettings.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ApplicationName" value="CSharpStudy"/>
  </appSettings>
</configuration>

 

posted on   BestNow  阅读(382)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示