[ACCEPTED]-Adding configuration to windows forms on .NET 5.0-.net-5

Accepted answer
Score: 36

Using .NET 5 or .NET Core configuration system in Windows Forms

You can follow these steps:

  1. Create a WinForms 20 .NET (5) Application

  2. Install Microsoft.Extensions.Hosting package.

    Instead 19 of the hosting package you may want to install 18 Microsoft.Extensions.Configuration.Json and Microsoft.Extensions.Configuration.Binder which are sufficient for this example.

  3. Add 17 an appsettings.json file to the project 16 root, set its build action to Content and 15 Copy to output directory to Always.

  4. Modify 14 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.Run(new Form1());

    Make sure you have added 13 using Microsoft.Extensions.Configuration;

  5. Set the content of the file:

      "MySettings": {
        "Text": "Title of the form",
        "BackColor": "255,0,0",
        "Size": "300,200"
  6. To read the 12 setting, open Form1.cs and paste the following 11 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)
        var mySettings = Program.Configuration.GetSection("MySettings").Get<MySettings>();
        this.Text = mySettings.Text;
        this.BackColor = mySettings.BackColor;
        this.Size = mySettings.Size;
  7. Run the application and see the result:

    enter image description here

Using Classic Settings for Windows Forms

And 10 to answer your last question: How are you 9 guys migrating the settings from 4.8 to 8 .NET 5.0 on Windows Forms apps?

It looks 7 like you are familiar with application/user 6 settings in .NET 4.x. The same is still 5 supported in .NET 5. Settings.settings file is part of the 4 default project template and it allows you 3 to create user settings and application 2 settings with designer support and many 1 more features. You can look at Application Settings for Windows Forms.

Score: 0

While looking for the same answer I noticed 10 that the document only mentions that the 9 runtime configuration is no longer supported 8 in app.config so you can still use it.

If 7 your app has an App.config file, remove 6 the <supportedRuntime>

The App.config file in .NET 5+ (and 5 .NET Core) is no longer used for runtime 4 configuration.

For me the main issue was 3 switching between different settings in 2 different configuration. I now use a App.config 1 per configuration as mentioned here.

More Related questions