Search code examples
c#asp.netconfigreadfilexml-configuration

Library to read config files (xml or json) that detects file´s changes


I have a XML configuration file like this:

<configuration>
<items>
    <item key="KEY_NAME">
        3
    </item>
</items>
</configuration>

I need some library to read (only read) the files values but can detect changes (for example, change value 3 for 5) without restart application.

I was using njupiter for that, but this project was deprecated. I found MiniFSWatcher, do you known some other library?

Thanks,


Solution

  • Why not use the official https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.8 class to watch the file system?

    Example below:

    using (FileSystemWatcher watcher = new 
    FileSystemWatcher())
        {
            watcher.Path = args[1];
    
            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;
    
            // Only watch text files.
            watcher.Filter = "*.xml";
    
            // Add event handlers.
            watcher.Changed += OnChanged;
    
            // Begin watching.
            watcher.EnableRaisingEvents = true;
    
            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }
    
    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e) =>
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }
    

    In the on changed event, you can reload the file and the values.

    This is the reason Njupiter is now deprecated.