2010-02-24 4 views
1

코드 숨김으로 C#을 사용하는 WPF 응용 프로그램을 작성 중이며 사용자에게 응용 프로그램의 특정 설정을 변경할 수있는 옵션을 제공하려고합니다. 끊임없이 읽고 쓸 수있는 응용 프로그램 내에 설정을 저장하는 표준이 있습니까?WPF 응용 프로그램 설정 파일

답변

3

app.config 파일을 쓸 수 있지만 (쓰기 위해 열려면 ConfigurationManager.OpenExeConfiguration을 사용) 실제로는 읽기 전용 설정을 거기에 저장하는 것이 좋습니다.

그것은 간단한 설정 클래스 쓰기 쉽다 : ConfigurationSection 클래스/저장 구성 파일에서 설정을 검색 할 수

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

사용을

참조 : 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 리소스 섹션을 참조하십시오.