Using .NET 5 or .NET Core configuration system in Windows Forms
You can follow these steps:
Create a WinForms .NET (5) Application
Install Microsoft.Extensions.Hosting
package.
Instead of the hosting package you may want to install Microsoft.Extensions.Configuration.Json
and Microsoft.Extensions.Configuration.Binder
which are sufficient for this example.
Add an appsettings.json file to the project root, set its build action to Content and Copy to output directory to Always.
Modify the program class:
static class Program
{
public static IConfiguration Configuration;
static void Main(string[] args)
{
//To register all default providers:
//var host = Host.CreateDefaultBuilder(args).Build();
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Make sure you have added using Microsoft.Extensions.Configuration;
Set the content of the file:
{
"MySettings": {
"Text": "Title of the form",
"BackColor": "255,0,0",
"Size": "300,200"
}
}
To read the setting, open Form1.cs and paste the following code:
public class MySettings
{
public string Text { get; set; }
public Color BackColor { get; set; }
public Size Size { get; set; }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var mySettings = Program.Configuration.GetSection("MySettings").Get<MySettings>();
this.Text = mySettings.Text;
this.BackColor = mySettings.BackColor;
this.Size = mySettings.Size;
}
Run the application and see the result:
Using Classic Settings for Windows Forms
And to answer your last question: How are you guys migrating the settings from 4.8 to .NET 5.0 on Windows Forms apps?
It looks like you are familiar with application/user settings in .NET 4.x. The same is still supported in .NET 5. Settings.settings
file is part of the default project template and it allows you to create user settings and application settings with designer support and many more features. You can look at Application Settings for Windows Forms.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…