WPF应用程序设置文件 [英] WPF Application Settings File

查看:272
本文介绍了WPF应用程序设置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的C#作为后面的代码WPF应用程序,我想给用户在应用程序中更改某些设置的选项。是否有一个应用程序中存储的设置,将进行读取和写入不断地标准?

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 settings within an application that will be read and written to constantly?

推荐答案

尽管在的app.config 文件可以被写入(使用的 ConfigurationManager.OpenExeConfiguration 来打开写),通常的做法是存储只读在那里设置。

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 =
        @"<?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);
        }
    }

}

这篇关于WPF应用程序设置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆