Как сделать чтение-запись настроек в(на) appsettings.json приложения?
Как сделать чтение-запись настроек в(на) appsettings.json приложения?
Проект: https://github.com/Dev65432/AppSettingsQ
Сейчас пробую так(не работает):
private async Task SaveSettingsExecuted()
{
_configuration["PathToImg"] = PathToImg;
var fgfg = _configuration["PathToImg"];
// Сохранение изменений в файл appsettings.json
IConfigurationRoot configurationRoot = (IConfigurationRoot)_configuration;
configurationRoot.Reload();
IsButtonEnabled = false;
}
Код
public class Deals2ViewModel : ViewModelBase
{
IConfiguration _configuration;
private IRepository<Deal> _dealsRepository;
private IRepository<Picture> _pictureRepository;
public Deals2ViewModel(IConfiguration configuration,
IRepository<Deal> DealsRepository,
IRepository<Picture> pictureRepository)
{
_configuration = configuration;
_dealsRepository = DealsRepository;
_pictureRepository = pictureRepository;
}
#region Command OpenAppSettingsCommand - Отобразить окно настроек
private ICommand _openAppSettingsCommand;
public ICommand OpenAppSettingsCommand
{
get
{
return _openAppSettingsCommand ??
(_openAppSettingsCommand = new RelayCommand(() => OnOpenAppSettingsExecuted()));
}
}
private async Task OnOpenAppSettingsExecuted()
{
AppSettingsViewModel appSettingsViewModel = new AppSettingsViewModel(_configuration);
AppSettingsWindow appSettingsWindow = new AppSettingsWindow();
appSettingsWindow.DataContext = appSettingsViewModel;
appSettingsWindow.Show();
}
#endregion
<DockPanel>
<GroupBox Header="Настройки приложения">
<Grid Margin="3">
<Grid.Resources>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="Grid.Column" Value="0">
<Setter Property="HorizontalAlignment" Value="Right"/>
<Setter Property="Margin" Value="0,0,2,0"/>
<Setter Property="FontWeight" Value="Bold"/>
</Trigger>
<Trigger Property="Grid.Column" Value="1">
<!--<Setter Property="Margin" Value="2,0,0,0"/>-->
<Setter Property="Margin" Value="20,20,20,20"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="Путь к папке с картинками: "/>
<TextBox Grid.Column="1" Grid.Row="0" Text="{Binding PathToImg,
UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Сохранить" Grid.Column="1" Grid.Row="1" Width="100"
Command="{Binding SaveSettingsCommand}"
IsEnabled="{Binding IsButtonEnabled}"
Background="{Binding ButtonColor}"
HorizontalAlignment="Right"/>
</Grid>
</GroupBox>
</DockPanel>
public class AppSettingsViewModel : ViewModelBase
{
IConfiguration _configuration;
public AppSettingsViewModel(IConfiguration configuration)
{
_configuration = configuration;
StartUp();
}
public void StartUp()
{
PathToImg = _configuration["PathToImg"];
IsButtonEnabled = false;
}
private string _pathToImg;
public string PathToImg
{
get
{
// _pathToFastStoneExe = _configuration["FastStonePath"];
return _pathToImg;
}
set
{
_pathToImg = value;
OnPropertyChanged(nameof(PathToImg));
UpdateButtonState();
}
}
#region Кнопка Сохранить
// private Brush _buttonColor = Brushes.Gray;
private Brush _buttonColor;
public Brush ButtonColor
{
get { return _buttonColor; }
set
{
_buttonColor = value;
OnPropertyChanged(nameof(ButtonColor));
}
}
private bool _isButtonEnabled = false;
public bool IsButtonEnabled
{
get { return _isButtonEnabled; }
set
{
_isButtonEnabled = value;
OnPropertyChanged(nameof(IsButtonEnabled));
}
}
private void UpdateButtonState()
{
IsButtonEnabled = true;
ButtonColor = Brushes.Red;
// ButtonColor = IsButtonEnabled ? Brushes.Green : Brushes.Gray;
// ButtonColor = IsButtonEnabled ? Brushes.Green : Brushes.Gray;
}
#endregion
#region Command SaveSettingsCommand - Команда загрузки данных из репозитория
/// <summary>Отобразить представление статистики</summary>
private ICommand _SaveSettingsCommand;
public ICommand SaveSettingsCommand
{
get
{
return _SaveSettingsCommand ??
(_SaveSettingsCommand = new RelayCommand(() => SaveSettingsExecuted()));
}
}
private async Task SaveSettingsExecuted()
{
_configuration["PathToImg"] = PathToImg;
var fgfg = _configuration["PathToImg"];
// Сохранение изменений в файл appsettings.json
IConfigurationRoot configurationRoot = (IConfigurationRoot)_configuration;
configurationRoot.Reload();
IsButtonEnabled = false;
}
#endregion
}
appsettings.json
{
"Database": {
"Type": "SQLite",
"ConnectionStrings": {
"MSSQL": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=AppsettingsWpf.db;Integrated Security=True",
"SQLite": "Data Source=Market.db"
}
},
"PathToImg": "AppFiles\\Imgs\\"
}
**Program.cs
class Program
{
[STAThread]
static void Main(string[] args)
{
var app = new App();
app.InitializeComponent();
app.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host
.CreateDefaultBuilder(args)
.ConfigureServices(App.ConfigureServices)
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
})
;
}
App.xaml.cs
public partial class App : Application
{
private static IHost __Host;
public static IHost Host => __Host
??= Program.CreateHostBuilder(Environment.GetCommandLineArgs()).Build();
public static IServiceProvider Services => Host.Services;
internal static void ConfigureServices(HostBuilderContext host,
IServiceCollection services) =>
services
.AddDatabase(host.Configuration.GetSection("Database"))
.AddRepositoriesInDB()
//.AddServices()
.AddViewModels()
;
protected override async void OnStartup(StartupEventArgs e)
{
// IsDesignTime = false;
var host = Host;
using (var scope = Services.CreateScope())
scope.ServiceProvider.GetRequiredService<DbInitializer>()
.InitializeAsync().Wait();
base.OnStartup(e);
await host.StartAsync();
}
protected override async void OnExit(ExitEventArgs e)
{
using var host = Host;
base.OnExit(e);
await host.StopAsync();
}
}
Ответы (1 шт):
Автор решения: AlexArs
→ Ссылка
Запись параметров в appsettings.json не рекомендована. Лучше используйте другой способ для сохранения настроек. По этой причине у C# по дефолту не реализована такая возможность.