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

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

问题描述

我正在框架 4.0 下用 C# 开发应用程序.

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

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

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.

我不想使用 configSource 从 app.config 引用此文件.

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.

我的意思的一个例子是允许您在 log4net.config 文件中写入配置的 log4net.

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 ?

更新:

根据 Kaido 的回答,我编写了实用程序类,可以读取自定义配置文件,并能够在文件系统上的文件发生更改时刷新配置内容.

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.

该类中的用法如下:

  1. 获取配置文件内容

  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"];

  • 在配置文件更改时收到通知

  • 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
    }
    

  • 在代码中,我使用 PostSharp 来验证构造函数输入参数以验证日志文件不为空并且文件存在.您可以更改代码以在代码中内联这些验证(尽管我建议使用 PostSharp 将应用程序分离为方面).

    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).

    代码如下:

        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);
    

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

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

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