2

我正在努力在我的 .NET C# 应用程序中实现用户设置的保存,在一种情况下,我只想保存一个设置。是否可以这样做,或者是我使用标准一次保存所有用户设置的唯一选择:

Properties.Settings.Default.Save();
4

1 回答 1

3

我更喜欢使用NINI,并将 XML 配置文件存储在Environment.SpecialFolder.ApplicationData.

可能不像 .NET 设置那么简单。反正我从来没有真正使用过它们。

例如,我有下面的课程。我需要做的就是获取或设置属性,它们会自动加载/保存:

using Nini.Config;

public class DbConfig : PropertyNotifierBase {
    private static readonly string PROGRAM_NAME = "programname";
    private static readonly string CONFIG_NAME = "Database";

    private static DbConfig _instance = new DbConfig();

    public static DbConfig Instance { get { return (_instance); } }

    private DbConfig() {
        SetupPaths();
        Source = new XmlConfigSource(FullConfigFilename);
        Source.AutoSave = true;
        CreateSectionsIfNeeded();
    }

    private void CreateSectionsIfNeeded() {
        if (Source.Configs["Database"] == null)
            Source.AddConfig("Database");
    }

    private void SetupPaths() {
        ConfigPath = DetermineConfigPath();
        ConfigFilename = String.Format("{0}.xml", CONFIG_NAME);
        Directory.CreateDirectory(ConfigPath);

        // Create an empty configuration file if it isn't there.
        if (!File.Exists(FullConfigFilename))
            File.WriteAllText(FullConfigFilename, "<Nini>\n</Nini>\n");
    }

    private IConfigSource Source { get; set; }

    public String ConfigPath { get; private set; }

    public String ConfigFilename { get; private set; }

    public String FullConfigFilename { get { return (Path.Combine(ConfigPath, ConfigFilename)); } }

    public String SqlServerInstance {
        get { return (Source.Configs["Database"].GetString("SqlServerInstance", @"somedefaultconnection")); }
        set { Source.Configs["Database"].Set("SqlServerInstance", value); NotifyPropertyChanged("SqlServerInstance"); }
    }

    public String SqlServerDatabase {
        get { return (Source.Configs["Database"].GetString("SqlServerDatabase", "somedatabasename")); }
        set { Source.Configs["Database"].Set("SqlServerDatabase", value); NotifyPropertyChanged("SqlServerDatabase"); }
    }

    public String SqlServerUsername {
        get { return (Source.Configs["Database"].GetString("SqlServerUsername", "someusername")); }
        set { Source.Configs["Database"].Set("SqlServerUsername", value); NotifyPropertyChanged("SqlServerUsername"); }
    }

    public String SqlServerPassword {
        get { return (Source.Configs["Database"].GetString("SqlServerPassword", "somepassword")); }
        set { Source.Configs["Database"].Set("SqlServerPassword", value); NotifyPropertyChanged("SqlServerPassword"); }
    }

    private string DetermineConfigPath() {
        String filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        filename += Path.DirectorySeparatorChar + PROGRAM_NAME;
        return (filename);
    }
}
于 2013-04-08T01:23:07.890 回答