在c#中保存单个用户设置

本文关键字:用户 设置 单个 保存 | 更新日期: 2023-09-27 18:07:51

我正致力于在我的。net c#应用程序中实现用户设置的保存,在一种情况下,我只想保存单个设置。是否有可能这样做,或者我唯一的选择是保存所有用户设置一次与标准:

Properties.Settings.Default.Save();

在c#中保存单个用户设置

我更喜欢使用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);
    }
}