在Properties.Settings.Default和Registry中存储设置

cli*_*uke 5 .net c# registry settings configuration

存储应用程序的用户设置有什么区别

Properties.Settings.Default

与将其存储在注册表中说

HKEY_CURRENT_USER\Software\{Application Name}

Dan*_*sha 5

属性.设置.默认值

在执行之间存储应用程序状态的常用技术是将其写入磁盘。有多种方法可以做到这一点,微软通过在 System.Configuration 命名空间中引入类来帮助用户管理保存应用程序状态(设置)。

Properties.Settings.Default是派生自ApplicationSettingBase的类的静态实例, 该类管理磁盘设置的读取和写入。用该[UserScopedSetting]属性标记的属性将保存到 C:\Users\user\AppData\Local\CompanyName\Hashed_AppName\version 中的 XML 文件中,用户可以读取和写入该文件。用该[ApplicationScopedSetting]属性标记的属性将保存到 app.config 文件中并且只能读取。

基本设置文件如下所示:

class FormSettings : ApplicationSettingsBase
{
    public WindowSettings() {}
    public WindowSettings(string settingsKey) : base(settingsKey) {}

    [UserScopedSettingAttribute()]
    [DefaultSettingValueAttribute("MyDefaultName")]
    public String Name
    {
        get { return (string)(this["Name"]); }
        set { this["Name"] = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以Properties.Settings.Default在 UI 中的“项目属性”->“设置”下设置值,也可以通过编程方式设置值Properties.Settings.Default

登记处

注册表是一个分层数据库,用于存储配置设置和选项,并将它们存储为键值对。请参阅维基百科了解更多信息。

可以通过静态Microsoft.Win32.Registry类访问注册表,该类允许您读取和写入值。例如:

public class RegistryExample 
{
    public static void Main()
    {
        const string rootUser = "HKEY_CURRENT_USER";
        const string subkey = "RegistryExample";
        const string keyName = String.Format("{0}\\{1}, rootUser, subkey);

        Registry.SetValue(keyName, "MyRegistryValue", 1234);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关示例,请参阅 MSDN 文档页面。正如其他人提到的那样,使用注册表有利有弊,但我认为值得再次说明的是,注册表是一个“安全”位置,您的用户将需要权限才能从中读取写入,因为设置文件不需要那些权限。


duD*_*uDE 0

保存 Properties.Settings.Default 等设置是唯一正确的方法。

注册表是不行的。您不确定使用您的应用程序的用户是否有足够的权限写入注册表。