Skip to content

Load configuration from a file and handling file´s changes #4

Description

Hi,

What do you think about to load the configuration from a file. The best part is that we can watch the file´s changes at runtime and reload the configuration like nJupiter.Configuration (deprecated project). With that, you don´t need to restart the application if any configuration changed or a new configuration was added.
I am thinking in somthing like this:

   `public abstract class CfgNode {
    
    ...

    private string CfgFilePath;
    private FileSystemWatcher CfgFileWatcher;
    private readonly object _cfgFileLocker = new object();
    
    ...
    
   public void LoadFromFile(string cfgFilePath)
    {
        if (!File.Exists(cfgFilePath)) throw new ArgumentException($"{nameof(cfgFilePath)} not exists.", nameof(cfgFilePath));

        var configurationsFilePathInfo = new FileInfo(cfgFilePath);

        CfgFileWatcher = new FileSystemWatcher
        {
            Path = configurationsFilePathInfo.DirectoryName,
            Filter = configurationsFilePathInfo.Name,
            NotifyFilter = NotifyFilters.LastWrite
        };

        CfgFileWatcher.Changed += OnCfgFileChanged;

        CfgFileWatcher.EnableRaisingEvents = true;

        CfgFilePath = cfgFilePath;

        var cfg = File.ReadAllText(CfgFilePath);

        Load(cfg);
    }

    private void OnCfgFileChanged(object source, FileSystemEventArgs e)
    {
        try
        {
            lock (_cfgFileLocker)
            {
                CfgFileWatcher.EnableRaisingEvents = false;

                var cfg = File.ReadAllText(CfgFilePath);

                Load(cfg);
            }
        }
        finally
        {
            CfgFileWatcher.EnableRaisingEvents = true;
        }
    }
  
    ...
}`

We will need System.IO.

Regards,
Darian

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions