Я разрабатываю приложение на С# в Framework 4.0.
В моем приложении я хотел бы создать отдельный файл конфигурации, который не является файлом app.config. Файл конфигурации содержит пользовательские разделы конфигурации, которые мы разработали для продукта.
Я не хочу ссылаться на этот файл из app.config с помощью configSource.
Я хочу загрузить его во время выполнения и прочитать его содержимое.
Пример того, что я имею в виду, это log4net, который позволяет вам записать конфигурацию в файле log4net.config.
Может ли кто-нибудь помочь, как это сделать без написания кода, который копирует код, который существует в рамках?
UPDATE:
на основе ответа от Kaido Я написал класс утилиты, который читает пользовательский файл конфигурации и имеет возможность обновлять содержимое Config при изменении файла в файловой системе.
Использование в этом классе выглядит следующим образом:
-
Получить содержимое файла конфигурации
// 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"];
-
Получить уведомления при изменении файла конфигурации
// 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 для разделения приложения на аспекты).
Вот код:
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
}
}