wpf write value to config file and read the persisted value

<Window x:Class="WpfApp26.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp26"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Grid.Row="0" HorizontalAlignment="Left" Content="Load Folder" FontSize="30" Click="LoadFolderCmd" />
<TextBlock x:Name="tb" Grid.Row="1" />
</Grid>
</Window>

 

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace WpfApp26
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string cfgKey = "cfgKey", cfgValue;
public MainWindow()
{
InitializeComponent();

}

void ReadValueFromConfig()
{
string str = ConfigurationManager.AppSettings[cfgKey];
tb.Text= str;
}

void WriteValueToConfig()
{
System.Configuration.Configuration config = ConfigurationManager.
OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Remove(cfgKey);
cfgValue = DateTime.Now.ToString("o");
config.AppSettings.Settings.Add(cfgKey, cfgValue);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);

// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
}

private void LoadFolderCmd(object sender, RoutedEventArgs e)
{
WriteValueToConfig();
ReadValueFromConfig();
}
}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2024-03-29 12:05  FredGrit  阅读(1)  评论(0编辑  收藏  举报