WPF Application Settings File

前端 未结 3 893
闹比i
闹比i 2021-02-11 08:36

I\'m writing a WPF application with C# as the code behind and I want to give the users the option to change certain settings in my application. Is there a standard for storing

3条回答
  •  甜味超标
    2021-02-11 09:08

    Despite the fact that the app.config file can be written to (using ConfigurationManager.OpenExeConfiguration to open for writing), the usual practice is to store read-only settings in there.

    It's 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 =
            @"
              
                  
                      
                      
                  
              ";
    
        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);
            }
    
        }
    
        /// 
        /// Retrieve a value by name.
        /// Returns the supplied DefaultValue if not found.
        /// 
        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;
        }
    
        /// 
        /// Write a config value by key
        /// 
        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);
            }
        }
    
    }
    

提交回复
热议问题