2010-02-24 39 views
1

我正在用C#編寫WPF應用程序作爲背後的代碼,我想讓用戶可以選擇更改我的應用程序中的某些設置。在應用程序中存儲設置的標準是否會不斷被讀取和寫入?WPF應用程序設置文件

回答

3

儘管可以寫入app.config文件(使用ConfigurationManager.OpenExeConfiguration打開寫入),但通常的做法是將只讀設置存儲在那裏。

可以很容易地編寫一個簡單的設置類:

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

} 
0

使用ConfigurationSection類來存儲/檢索配置文件設置

見:How to: Create Custom Configuration Sections Using ConfigurationSection

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

你可以試試窗口\ XAML的資源部分。