WPF Application Settings File

I am writing a WPF application with C # as the code behind, and I want to give users the ability to change certain settings in my application. Is there a standard for storing settings in an application that will be constantly read and written?

+1
source share
3 answers

Although the app.config file can be written to (using ConfigurationManager.OpenExeConfiguration to open for writing), it is common practice to save read-only settings.

It is easy to write a simple settings class:

 public sealed class Settings { private readonly string _filename; private readonly XmlDocument _doc = new XmlDocument(); private const string emptyFile = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <appSettings> <add key=""defaultkey"" value=""123"" /> <add key=""anotherkey"" value=""abc"" /> </appSettings> </configuration>"; public Settings(string path, string filename) { // strip any trailing backslashes... while (path.Length > 0 && path.EndsWith("\\")) { path = path.Remove(path.Length - 1, 1); } _filename = Path.Combine(path, filename); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!File.Exists(_filename)) { // Create it... _doc.LoadXml(emptyFile); _doc.Save(_filename); } else { _doc.Load(_filename); } } /// <summary> /// Retrieve a value by name. /// Returns the supplied DefaultValue if not found. /// </summary> public string Get(string key, string defaultValue) { XmlNode node = _doc.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']"); if (node == null) { return defaultValue; } return node.Attributes["value"].Value ?? defaultValue; } /// <summary> /// Write a config value by key /// </summary> public void Set(string key, string value) { XmlNode node = _doc.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']"); if (node != null) { node.Attributes["value"].Value = value; _doc.Save(_filename); } } } 
+3
source

use the ConfigurationSection class to store / retrieve settings from the configuration file

see below: How to create custom configuration sections using ConfigurationSection

 public class ColorElement : ConfigurationElement { [ConfigurationProperty("background", DefaultValue = "FFFFFF", IsRequired = true)] [StringValidator(InvalidCharacters = " ~!@ #$%^&*()[]{}/;'\"|\\GHIJKLMNOPQRSTUVWXYZ", MinLength = 6, MaxLength = 6)] public String Background { get { return (String)this["background"]; } set { this["background"] = value; } } } 
0
source

You can try the \ page Resources window on XAML.

0
source

Source: https://habr.com/ru/post/1344527/


All Articles