23

I'm migrating an existing windows forms C# app to .NET 5.0 and I'm trying to follow the instrutions presented on the migration docs. Everything is working ok, but there's still one thing to do: migrate the debug/release settings from app.config files.

I've thought about reusing NET Core's IConfiguration, but adding the Microsoft.Extensions.Configuration nuget package to the project (so that I'm able to create a ConfigurationBuilder instance) seems to break everything (for instance, using System; will start generating compile errors).

Any ideas on what's going on? How are you guys migrating the settings from 4.8 to .NET 5.0 on Windows Forms apps?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Luis Abreu
  • 4,008
  • 9
  • 34
  • 63
  • "adding the Microsoft.Extensions.Configuration nuget package to the project (so that I'm able to create a ConfigurationBuilder instance) seems to break everything" is not a problem statement that we can help with. – Ian Kemp Jan 11 '21 at 22:40

2 Answers2

52

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

You can follow these steps:

  1. Create a WinForms .NET (5) Application

  2. 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.

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

  4. 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;

  5. Set the content of the file:

    {
      "MySettings": {
        "Text": "Title of the form",
        "BackColor": "255,0,0",
        "Size": "300,200"
      }
    }
    
  6. 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;
    }
    
  7. Run the application and see the result:

    enter image description here

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • I've done something along these lines to make it work. However, CS+Resharper still don't work properly when you're migrating the solution. Btw, if I decided to improve it by using host so that I get all the goodies we're used to in asp.net, do you know if there's alreayd a valid lifecycle for it ? – Luis Abreu Jan 12 '21 at 11:22
  • Well, for me it worked seamless. About host, I haven't tried in WinForms myself, but you can take a look at this [blog post](https://www.thecodebuzz.com/loading-configuration-ini-xml-json-net-core-console-winform). – Reza Aghaei Jan 12 '21 at 13:09
  • Yes, I've seen it...but the integration with the host isn't that great. However, I'm tempted to reuse this https://github.com/alex-oswald/WindowsFormsLifetime and see if it works :) – Luis Abreu Jan 12 '21 at 14:37
  • How does this work for multiple environments? – Bob W Aug 26 '22 at 22:33
  • @BobW If you use `Host.CreateDefaultBuilder(args).Build();` then it respects to different appsettings.ENVIRONMENT.json files. [Default application configuration sources](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?source=recommendations&view=aspnetcore-6.0&WT.mc_id=DT-MVP-5003235#default-application-configuration-sources) – Reza Aghaei Aug 27 '22 at 08:49
  • Thanks. Yeah, I was able to do that. – Bob W Aug 31 '22 at 14:49
  • this worked fine to .net 7 too – Porter Mar 01 '23 at 17:30
0

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

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

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

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

Chevalric
  • 79
  • 7