.NET6读取自定义配置文件到Configuration中
微软只提供了以下可以读取配置的方式,其中文件配置只能读取INI、JSON和XML文件,如果我想对其他自定义文件进行读取,那么我们可以使用自定义配置提供程序进行配置
比如,我想对以下格式的文件进行读取,而且只想读取上半部分内容
auto eth0 iface eth0 inet static address 10.50.50.111 netmask 255.255.255.0 gateway 10.50.50.1 dns-nameserver 8.8.8.8 dns-nameserver 114.114.114.114 auto eth1 iface eth1 inet static address 192.168.3.110 netmask 255.255.255.0 gateway 192.168.3.1 dns-nameserver 8.8.8.8 dns-nameserver 114.114.114.114
1、新建CustomConfigurationProvider文件,继承自ConfigurationProvider
核心:对Data赋值
public class CustomConfigurationProvider : ConfigurationProvider { private readonly string _filePath; private readonly int _line; public CustomConfigurationProvider(string filePath,int line) { _filePath = filePath; _line = line; } public override void Load() { if (!File.Exists(_filePath)) return; var line = 0; var dic = new Dictionary<string, string>(); foreach (var str in File.ReadAllLines(_filePath)) { if (line >=_line) break; var strArry = str.Split(" "); if (strArry.Length > 1) dic[strArry[0]] = strArry[1]; line++; } Data = dic; } }
2、新建CustomConfigurationSource文件,继承自IConfigurationSource
public class CustomConfigurationSource : IConfigurationSource { private readonly string _filePath; private readonly int _line; public CustomConfigurationSource(string filePath,int line) { _filePath = filePath; _line = line; } public IConfigurationProvider Build(IConfigurationBuilder builder) => new CustomConfigurationProvider(_filePath, _line); }
3、新建扩展文件ConfigurationExtensions
public static class ConfigurationExtensions { /// <summary> /// 读取自定义格式配置文件 /// </summary> /// <param name="builder"></param> /// <param name="filePath">文件目录</param> /// <param name="line">读取到第几行为止</param> /// <returns></returns> public static IConfigurationBuilder AddCustomConfiguration( this IConfigurationBuilder builder,string filePath,int line) { return builder.Add(new CustomConfigurationSource(filePath,line)); } }
4、在程序中读取
var networkConfig = new ConfigurationBuilder() .AddCustomConfiguration(Path.Combine("netowrk", "interfaces"),7) .Build()
好啦,是不是很简单?想读取其他类型的文件,只需在ConfigurationProvider处进行编写自己的方法即可。
参考文档: