c# Мониторинг изменения файла

Необходимо мониторить изменения файла appsettings.json. Вот код, который я использую для мониторинга.

var builder = WebApplication.CreateBuilder(args);
var serviceProvider = builder.Services.BuildServiceProvider();
ConfigureMonitoring(builder.Services, builder.Configuration, serviceProvider);

private static void ConfigureMonitoring(IServiceCollection services, ConfigurationManager configuration, IServiceProvider serviceProvider)
{
    services.Configure<AppSettingsOptions>(configuration.GetSection("AppSettings"));

    var appSettings = serviceProvider.GetRequiredService<IOptions<AppSettingsOptions>>().Value;

    var fileProvider = configuration.GetFileProvider();
    var changeToken = fileProvider?.Watch("appsettings.json");
    changeToken?.RegisterChangeCallback(OnAppSettingsChanged, configuration);

    static void OnAppSettingsChanged(object state)
    {
        var configuration = (IConfiguration)state;
        var appSettings = configuration.GetSection("AppSettings").Get<AppSettingsOptions>();
        var documentsPath = appSettings.DocumentsPath;

        if (string.IsNullOrEmpty(documentsPath))
            Log.Warning($"{nameof(AppSettingsOptions.DocumentsPath)} cant be NullOrWhiteSpace");
        else
            Log.Information($"{nameof(AppSettingsOptions.DocumentsPath)} update");
    }
}

Код файла, который должен обновляться при обновлении файла appsettings.json

public class AppSettingsOptions
{
    public string DocumentsPath { get; set; }
}

Метод OnAppSettingsChanged не вызывается. Что я делаю не так?


Ответы (1 шт):

Автор решения: Frehzy
[ApiController]
[Route("[controller]")]
public class FileWatcherController : ControllerBase
{
    private readonly IHostApplicationLifetime _appLifetime;

    public FileWatcherController(IHostApplicationLifetime appLifetime)
    {
        _appLifetime = appLifetime;
        InitializeFileWatcher();
    }

    //тут потом добавлю логику по изменению файла конфигурации сервера

    private void InitializeFileWatcher()
    {
        string filePath = Path.Combine(Environment.CurrentDirectory, "appsettings.json");

        using (FileSystemWatcher watcher = CreateFileSystemWatcher(filePath))
        {
            _appLifetime.ApplicationStarted.Register(() => watcher.EnableRaisingEvents = true);
        }
    }

    private FileSystemWatcher CreateFileSystemWatcher(string filePath)
    {
        FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath), Path.GetFileName(filePath));
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Changed += OnFileChanged;

        return watcher;
    }

    private void OnFileChanged(object sender, FileSystemEventArgs e)
    {
        if (!IsFileValid(e.FullPath))
            Log.Warning("Файл некорректен.");
    }

    private bool IsFileValid(string filePath)
    {
        return true;
    }
}
→ Ссылка