What's the best practice to read values from appsettings in a windows forms .net 7 application? I have found examples for console application but it doesn't work.
CodePudding user response:
Assuming this is for appsettings.json
, using the following file
{
"Role": {
"IsAdmin": true
},
"LogOptions": {
"Use": true,
"Destination": "LogFile",
"LogFileName": "logs.txt"
},
"FormSettings": {
"Title": "Code sample",
"FullScreen": "true"
}
}
Use the following classes to get values from appsettings.json
public class FormSettings
{
public string Title { get; set; }
public bool FullScreen { get; set; }
}
public class Role
{
public bool IsAdmin { get; set; }
}
public class Logging
{
public bool Use { get; set; }
public LoggingDestination Destination { get; set; }
public string LogFileName { get; set; }
}
public enum LoggingDestination
{
DebugWindow,
LogFile,
None
}
Class to read settings from appsettings.json
public class AppSettings
{
private static ConfigurationBuilder _configBuilder;
public static Logging GetLogOptions()
{
Build();
return InitOptions<Logging>("LogOptions");
}
public static Role Role()
{
Build();
return InitOptions<Role>("Role");
}
public static FormSettings Settings()
{
Build();
return InitOptions<FormSettings>("FormSettings");
}
private static IConfigurationRoot Build()
{
if (_configBuilder is not null) return _configBuilder.Build();
_configBuilder = new ConfigurationBuilder();
_configBuilder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true);
return _configBuilder.Build();
}
public static T InitOptions<T>(string section) where T : new()
=> Build().GetSection(section).Get<T>();
}
Usage
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Text = AppSettings.Role().IsAdmin
? AppSettings.Settings().Title " (Admin)"
: AppSettings.Settings().Title ;
}
private void GetLogInfoButton_Click(object sender, EventArgs e)
{
if (AppSettings.GetLogOptions().Use && AppSettings.GetLogOptions().Destination == LoggingDestination.LogFile)
{
MessageBox.Show($"{AppSettings.GetLogOptions().LogFileName}");
}
}
}
NuGet packages
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json