c# - 向 .NET 5.0 上的 Windows 窗体添加配置

标签 c# winforms .net-5

我正在将现有的 Windows 窗体 C# 应用程序迁移到 .NET 5.0,并且我正在尝试按照 migration docs 上提供的说明进行操作。 .一切正常,但还有一件事要做:从 app.config 文件迁移调试/发布设置。
我已经考虑过重用 NET Core 的 IConfiguration ,但是将 Microsoft.Extensions.Configuration nuget 包添加到项目中(以便我能够创建 ConfigurationBuilder 实例)似乎会破坏一切(例如,using System; 将开始生成编译错误)。
关于发生了什么的任何想法?你们如何将 Windows 窗体应用程序上的设置从 4.8 迁移到 .NET 5.0?

最佳答案

在 Windows 窗体中使用 .NET 5 或 .NET Core 配置系统
您可以按照以下步骤操作:

  • 创建 WinForms .NET (5) 应用程序
  • 安装 Microsoft.Extensions.Hosting包裹。
    您可能想要安装 Microsoft.Extensions.Configuration.Json 而不是托管包和 Microsoft.Extensions.Configuration.Binder这对于这个例子来说已经足够了。
  • 将 appsettings.json 文件添加到项目根目录,将其构建操作设置为 Content 并将复制到输出目录设置为 Always。
  • 修改程序类:
    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());
        }
    }
    
    确保您已添加 using Microsoft.Extensions.Configuration;
  • 设置文件内容:
    {
      "MySettings": {
        "Text": "Title of the form",
        "BackColor": "255,0,0",
        "Size": "300,200"
      }
    }
    
  • 要读取设置,请打开 Form1.cs 并粘贴以下代码:
    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;
    }
    
  • 运行应用程序并查看结果:
    enter image description here

  • 使用 Windows 窗体的经典设置
    并回答您的最后一个问题:你们如何将 Windows 窗体应用程序上的设置从 4.8 迁移到 .NET 5.0?
    您似乎熟悉 .NET 4.x 中的应用程序/用户设置。 .NET 5 中仍然支持相同的功能。Settings.settings文件是默认项目模板的一部分,它允许您使用设计器支持和更多功能创建用户设置和应用程序设置。你可以看看Application Settings for Windows Forms .

    关于c# - 向 .NET 5.0 上的 Windows 窗体添加配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65669920/

    相关文章:

    c# - Jquery 模态未调整大小

    c# - WPF JumpTask 另一个图标不是默认图标吗?

    c# - 如何在身份服务器 4 的客户端获得额外的声明?

    oracle - ODP.Net 驱动程序在 .NET Core 5.0 上抛出异常

    c# - .NET5辅助服务模板的NLog设置

    asp.net-core - 更改在 kubernetes 上运行的 net core 应用程序的配置

    c# - 打开包进行写入时出现奇怪的错误

    c# - 将 DataGridView 绑定(bind)到 List<T> 不显示数据

    c# - 从控件的字体中删除 FontStyle Bold

    c# - 从 Windows 窗体应用程序打开 AutoCAD