阅读在C#中自定义配置文件(框架4.0) [英] Read custom configuration file in C# (Framework 4.0)

查看:198
本文介绍了阅读在C#中自定义配置文件(框架4.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我Framework 4.0中下开发的C#应用​​程序。

在我的应用程序,我想创建单独的配置文件,是不是app.config文件。配置文件包含我们的产品开发的自定义配置部分。

我不希望从使用configSource在app.config引用此文件。

我想在运行时加载它,阅读它的内容。

要明白我的意思的一个例子是,让你写在log4net.config文件中的配置log4net的。

谁能帮助该怎么做,而无需编写code,它mimcs的code存在于框架?

谢谢,
Koby

更新:

根据从海道我写的实用工具类,它读取自定义配置文件,并有刷新配置内容的能力答案

在对文件系统更改该文件。

在这个类的用法如下:


  1. 获取配置文件内容

      //创建配置读卡器,一旦读取文件
    VAR configFileReader =新CustomConfigurationFileReader(C:\\\\ myconfig.config);
    无功配置= configFileReader.Config;//你想使用的配置对象的任何行动,如:
    config.GetSection(my.custom.section);// 要么,
    VAR someVal = config.AppSettings.Settings [someKey];


  2. 获取通知时配置文件更改

      //创建一个通知configuraiton文件发生更改时配置读卡器
    VAR configFileReader =新CustomConfigurationFileReader(C:\\\\ myconfig.config,真正的);//注册到FileChanged事件
    configFileReader.FileChanged + =一个MyEventHandler;...私人无效MyEventHanler(对象发件人,EventArgs的发送)
    {
         //您可以放心地在这里访问的配置属性,它已经包含了新的内容
    }


在code我用PostSharp为了验证构造函数的输入参数,以验证该日志文件不是null,该文件存在。您可以更改code,使在code的验证在线(虽然我建议使用PostSharp到单独的应用程序方面)。

下面是code:

 使用系统;
    使用System.Configuration;
    使用System.IO;
    使用CSG.Core.Validation;    命名空间CSG.Core.Configuration
    {
        ///<总结>
        ///客户读取配置文件
        ///< /总结>
        公共类CustomConfigurationFileReader
        {
            //默认情况下,不通知的文件更改
            私人常量布尔DEFAULT_NOTIFY_BEHAVIOUR = FALSE;            #地区字段            //配置文件名
            私人只读字符串_configFileName;            ///<总结>
            ///当configuraiton文件被修改引发
            ///< /总结>
            公共事件System.EventHandler FileChanged;            #endregion场            #区域构造            ///<总结>
            ///初始化CustomConfigurationFileReader类通知的新实例
            ///当配置文件更改。
            ///< /总结>
            ///< PARAM NAME =configFileName>将完整路径的自定义配置文件< /参数>
            公共CustomConfigurationFileReader(字符串configFileName)
                :这个(configFileName,DEFAULT_NOTIFY_BEHAVIOUR)
            {
            }            ///<总结>
            ///初始化CustomConfigurationFileReader类的新实例
            ///< /总结>
            ///< PARAM NAME =configFileName>将完整路径的自定义配置文件< /参数>
            ///< PARAM NAME =notifyOnFileChange>指示是否提高FileChange事件时configuraiton文件的更改和LT; /参数>
            [ValidateParameters]
            公共CustomConfigurationFileReader([NOTNULL,FILEEXISTS]字符串configFileName,布尔notifyOnFileChange)
            {
                //设置配置文件名
                _configFileName = configFileName;                //读取配置文件
                ReadConfiguration();                //开始看配置文件(如果notifyOnFileChanged为true)
                如果(notifyOnFileChange)
                    WatchConfigFile();
            }            #endregion构造            ///<总结>
            ///获取该重新presents配置文件的内容的配置
            ///< /总结>
            公共System.Configuration.Configuration配置
            {
                得到;
                组;
            }            #地区的辅助方法            ///<总结>
            ///留意变化configuraiton文件
            ///< /总结>
            私人无效WatchConfigFile()
            {
                VAR观察家=新FileSystemWatcher的(_configFileName);
                watcher.Changed + = ConfigFileChangedEvent;
            }            ///<总结>
            ///读取配置文件
            ///< /总结>
            公共无效ReadConfiguration()
            {
                //创建配置文件映射指向配置文件
                VAR configFileMap =新ExeConfigurationFileMap
                {
                    ExeConfigFilename = _configFileName
                };                //创建一个包含自定义配置文件的内容配置对象
                配置= ConfigurationManager.OpenMappedExeConfiguration(configFileMap,ConfigurationUserLevel.None);
            }            ///<总结>
            ///时调用配置文件更改。
            ///< /总结>
            ///< PARAM NAME =发件人>< /参数>
            ///< PARAM NAME =E>< /参数>
            私人无效ConfigFileChangedEvent(对象发件人,FileSystemEventArgs E)
            {
                //检查文件更改事件有监听器
                如果(FileChanged!= NULL)
                    //引发事件
                    FileChanged(这一点,新的EventArgs());
            }            #endregion辅助方法
        }
    }


解决方案

  //地图漫游配置文件。这个
      //使应用程序能够访问
      //配置文件使用
      // System.Configuration.Configuration类
      ExeConfigurationFileMap configFileMap =
        新ExeConfigurationFileMap();
      configFileMap.ExeConfigFilename =
        roamingConfig.FilePath;      //获取映射配置文件。
      配置配置=
        ConfigurationManager.OpenMappedExeConfiguration(
          configFileMap,ConfigurationUserLevel.None);

从<一个href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx\">http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

I am developing an application in C# under Framework 4.0.

In my application I would like to create separate configuration file that is not the app.config file. The configuration file contains custom configuration sections we developed for the product.

I don't want to reference this file from the app.config using the configSource.

I want to load it at runtime and read it's content.

An example to what I mean is the log4net that allow you to write the configuration in the log4net.config file.

Can anyone help how to do that without writing code that mimcs the code that exists in the framework ?

Thanks, Koby

UPDATE:

based on the answer from Kaido I wrote utility class that reads custom configuration file and has the ability to refresh the Config content when the file on the file system changes.

The usage in this class is as follows:

  1. Get the configuration file content

    // Create configuration reader that reads the files once
    var configFileReader = new CustomConfigurationFileReader("c:\\myconfig.config");
    var config = configFileReader.Config;
    
    // Do any action you want with the config object like:
    config.GetSection("my.custom.section");
    
    // or,
    var someVal = config.AppSettings.Settings["someKey"];
    

  2. Get notifications when the configuration file changes

    // Create configuration reader that notifies when the configuraiton file changes
    var configFileReader = new CustomConfigurationFileReader("c:\\myconfig.config", true);
    
    // Register to the FileChanged event
    configFileReader.FileChanged += MyEventHandler;
    
    ...
    
    private void MyEventHanler(object sender, EventArgs e)
    {
         // You can safely access the Config property here, it is already contains the new content
    }
    

In the code I used PostSharp in order to validate the constructor input parameter to verify that the log file is not null and that the file exists. You can change the code to make those validation inline in the code (although I recomend to use PostSharp to seperate the application to aspects).

Here is the code:

    using System;
    using System.Configuration;
    using System.IO;
    using CSG.Core.Validation;

    namespace CSG.Core.Configuration
    {
        /// <summary>
        /// Reads customer configuration file
        /// </summary>
        public class CustomConfigurationFileReader
        {
            // By default, don't notify on file change
            private const bool DEFAULT_NOTIFY_BEHAVIOUR = false;

            #region Fields

            // The configuration file name
            private readonly string _configFileName;

            /// <summary>
            /// Raises when the configuraiton file is modified
            /// </summary>
            public event System.EventHandler FileChanged;

            #endregion Fields

            #region Constructor

            /// <summary>
            /// Initialize a new instance of the CustomConfigurationFileReader class that notifies 
            /// when the configuration file changes.
            /// </summary>
            /// <param name="configFileName">The full path to the custom configuration file</param>
            public CustomConfigurationFileReader(string configFileName)
                : this(configFileName, DEFAULT_NOTIFY_BEHAVIOUR)
            {            
            }        

            /// <summary>
            /// Initialize a new instance of the CustomConfigurationFileReader class
            /// </summary>
            /// <param name="configFileName">The full path to the custom configuration file</param>
            /// <param name="notifyOnFileChange">Indicate if to raise the FileChange event when the configuraiton file changes</param>
            [ValidateParameters]
            public CustomConfigurationFileReader([NotNull, FileExists]string configFileName, bool notifyOnFileChange)
            {
                // Set the configuration file name
                _configFileName = configFileName;

                // Read the configuration File
                ReadConfiguration();

                // Start watch the configuration file (if notifyOnFileChanged is true)
                if(notifyOnFileChange)
                    WatchConfigFile();
            }

            #endregion Constructor        

            /// <summary>
            /// Get the configuration that represents the content of the configuration file
            /// </summary>
            public System.Configuration.Configuration Config
            {
                get;
                set;
            }

            #region Helper Methods

            /// <summary>
            /// Watch the configuraiton file for changes
            /// </summary>
            private void WatchConfigFile()
            {
                var watcher = new FileSystemWatcher(_configFileName);
                watcher.Changed += ConfigFileChangedEvent;
            }

            /// <summary>
            /// Read the configuration file
            /// </summary>
            public void ReadConfiguration()
            {
                // Create config file map to point to the configuration file
                var configFileMap = new ExeConfigurationFileMap
                {
                    ExeConfigFilename = _configFileName
                };

                // Create configuration object that contains the content of the custom configuration file
                Config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
            }        

            /// <summary>
            /// Called when the configuration file changed.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void ConfigFileChangedEvent(object sender, FileSystemEventArgs e)
            {
                // Check if the file changed event has listeners
                if (FileChanged != null)
                    // Raise the event
                    FileChanged(this, new EventArgs());
            }

            #endregion Helper Methods
        }
    }

解决方案

 // Map the roaming configuration file. This
      // enables the application to access 
      // the configuration file using the
      // System.Configuration.Configuration class
      ExeConfigurationFileMap configFileMap =
        new ExeConfigurationFileMap();
      configFileMap.ExeConfigFilename = 
        roamingConfig.FilePath;

      // Get the mapped configuration file.
      Configuration config =
        ConfigurationManager.OpenMappedExeConfiguration(
          configFileMap, ConfigurationUserLevel.None);

from http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

这篇关于阅读在C#中自定义配置文件(框架4.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆