1.通过ConfigurationManager来进行读取Config文件中的AppSettings节点
public struct AppSetting
{
public bool IsOK { get; set; }
public string Value { get; set; }
}
/// <summary>
/// 获取ConfigurationManager.AppSettings中的值
/// </summary>
/// <param name="name">keyName</param>
/// <returns></returns>
public static AppSetting TryGetAppSetting(string name)
{
AppSetting appSetting = new AppSetting();
if (ConfigurationManager.AppSettings.AllKeys.Contains(name))
{
appSetting.Value = ConfigurationManager.AppSettings[name];
appSetting.IsOK = true;
}
else
{
appSetting.IsOK = false;
}
return appSetting;
}
/// <summary>
/// 增加或者修改appSettings
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public static void TrySetAppSetting(string name, string value)
{
ConfigurationManager.AppSettings [name] = value;
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
Assembly assembly = Assembly.GetCallingAssembly();
Uri uri = new Uri(Path.GetDirectoryName(assembly.CodeBase));
map.ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".exe.config");
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, 0);
if (config.AppSettings.Settings.AllKeys.Contains(name))
{
config.AppSettings.Settings[name].Value = value;
}
else
{
config.AppSettings.Settings.Add(name,value) ;
}
config.Save(System.Configuration.ConfigurationSaveMode.Modified);
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}
2.使用ContainerBuilder 读取固定配置
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration.Json;
/// <summary>
/// 配置服务
/// </summary>
/// <param name="containerBuilder"></param>
private static void ConfigureServices(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterType<MainWindow>();
containerBuilder.RegisterInstance(ILogger);
containerBuilder.RegisterType<CancellationTokenSource>();
Configuration = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
containerBuilder.RegisterInstance(Configuration.GetSection("AppSettings").Get<AppSettings>());
containerBuilder.RegisterInstance(Configuration.GetSection("ScanSettings").Get<ScanSettings>());
Services = containerBuilder.Build();
App.ILogger.Info("配置和注册");
}
public class AppSettings
{
public double 属性{ get; set; }
public double 属性{ get; set; }
public double 属性{ get; set; }
public double 属性{ get; set; }
public double 属性{ get; set; }
}
public class ScanSettings
{
public double 属性{ get; set; }
public double 属性{ get; set; }
public double 属性{ get; set; }
}