Чтение настраиваемого файла конфигурации на C # (Framework 4.0)

Я разрабатываю приложение на C # в рамках Framework 4.0.

В моем приложении я хотел бы создать отдельный файл конфигурации, который не является файлом app.config. Файл конфигурации содержит пользовательские разделы конфигурации, которые мы разработали для продукта.

Я не хочу ссылаться на этот файл из app.config с помощью configSource.

Я хочу загрузить его во время выполнения и прочитать его содержимое.

Примером того, что я имею в виду, является log4net, который позволяет вам записывать конфигурацию в файл log4net.config.

Кто-нибудь может помочь, как это сделать что без написания кода, который имитирует код, существующий в структуре?

ОБНОВЛЕНИЕ:

на основе ответа от Кайдо Я написал служебный класс, который читает пользовательский файл конфигурации и имеет возможность обновлять Содержимое конфигурации при изменении файла в файловой системе.

Этот класс используется следующим образом:

  1. Получить содержимое файла конфигурации

     // Создать средство чтения конфигурации, которое считывает файлы один раз
    var configFileReader = new CustomConfigurationFileReader ("c: \\ myconfig.config");
    вар config = configFileReader.Config;
    
     // Выполните любое действие с объектом конфигурации, например:
    config.GetSection ("my.custom.section");
    
     // или,
    var someVal = config.AppSettings.Settings ["someKey"];
     
  2. Получение уведомлений при изменении файла конфигурации

     // Создание программы чтения конфигурации, которая уведомляет об изменении файла конфигурации
    var configFileReader = new CustomConfigurationFileReader ("c: \\ myconfig.config", истина);
    
     // Зарегистрируемся на событие FileChanged
    configFileReader.FileChanged + = MyEventHandler;
    
     ...
    
    private void MyEventHanler (отправитель объекта, EventArgs e)
     {
      // Вы можете безопасно получить доступ к свойству Config здесь, оно уже содержит новый контент
     }
     

В коде я использовал PostSharp для проверки входного параметра конструктора, чтобы убедиться, что файл журнала не равен нулю и что файл существует. Вы можете изменить код, чтобы сделать эту проверку встроенной в код (хотя я рекомендую использовать PostSharp для разделения приложения на аспекты).

Вот код:

    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
        }
    }
37
задан johnnyRose 18 July 2017 в 17:46
поделиться