如何在运行时获取appSettings.json路径供FileSystemWatcher实例使用
运行时获取appSettings.json路径的实现方案
ASP.NET Core 场景(最推荐方案)
- 通过注入
IHostEnvironment(.NET Core 3.0+通用)/IWebHostEnvironment拼接路径,该方案不会受程序工作目录变更影响,准确性最高
// 程序启动阶段直接获取(.NET 6+ 顶层语句写法) var builder = WebApplication.CreateBuilder(args); string appSettingsPath = Path.Combine(builder.Environment.ContentRootPath, "appSettings.json"); // 服务/控制器中运行时获取 public class ConfigWatchService { private readonly string _appSettingsPath; public ConfigWatchService(IHostEnvironment hostEnv) { _appSettingsPath = Path.Combine(hostEnv.ContentRootPath, "appSettings.json"); } }
- 从已加载的配置源中直接提取路径,无需手动拼接,适配自定义配置路径的场景
var configRoot = builder.Configuration as IConfigurationRoot; string? appSettingsPath = configRoot?.Providers .OfType<JsonConfigurationProvider>() .FirstOrDefault(p => p.Source.Path.Equals("appsettings.json", StringComparison.OrdinalIgnoreCase)) ?.Source?.FileProvider ?.GetFileInfo("appsettings.json")?.PhysicalPath;
如果需要监听多环境配置文件(如appsettings.Development.json),修改上面的文件名匹配规则即可
普通.NET 控制台/非Web场景
优先用AppContext基础目录拼接,避免工作目录变更导致路径错误:
string appSettingsPath = Path.Combine(AppContext.BaseDirectory, "appSettings.json");
不要使用Directory.GetCurrentDirectory()获取路径,程序运行过程中工作目录可能被第三方逻辑修改,导致路径匹配失败
绑定到FileSystemWatcher的示例
拿到路径后直接初始化监听实例即可:
var watcher = new FileSystemWatcher( path: Path.GetDirectoryName(appSettingsPath), filter: Path.GetFileName(appSettingsPath)) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size, EnableRaisingEvents = true }; // 绑定配置变更事件 watcher.Changed += (sender, e) => { // 自定义配置更新后的处理逻辑 Console.WriteLine("appSettings.json 配置已更新"); };
内容的提问来源于stack exchange,提问作者littlebit
相关产品推荐
相关产品推荐

