在windows forms .net 6应用程序中读取和使用appsettings参数,

vuktfyat  于 2022-12-05  发布在  .NET
关注(0)|答案(1)|浏览(195)

在windows forms.net7应用程序中从appsettings读取值的最佳实践是什么?我找到了控制台应用程序的例子,但它不起作用。

lb3vh1jj

lb3vh1jj1#

假设这是针对appsettings.json的,使用以下文件

{
  "Role": {
    "IsAdmin": true
  },
  "LogOptions": {
    "Use": true,
    "Destination": "LogFile",
    "LogFileName": "logs.txt"
  },
  "FormSettings": {
    "Title": "Code sample",
    "FullScreen": "true"
  }
}

使用以下类从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
}

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>();
}

用途

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软件包

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

相关问题