在C#中读取默认应用程序设置

我有自定义网格控件的许多应用程序设置(在用户范围内)。 其中大多数是颜色设置。 我有一个表单,用户可以自定义这些颜色,我想添加一个按钮,以恢复默认颜色设置。 如何阅读默认设置?

例如:

  1. 我在Properties.Settings有一个名为CellBackgroundColor的用户设置。
  2. 在设计时,我使用IDE将Color.White的值设置为Color.White
  3. 用户在我的程序CellBackgroundColor Color.Black设置为Color.Black
  4. 我使用Properties.Settings.Default.Save()保存设置。
  5. 用户单击“ Restore Default Colors按钮。

现在, Properties.Settings.Default.CellBackgroundColor返回Color.Black 。 我该如何回到Color.White

@ozgur,

 Settings.Default.Properties["property"].DefaultValue // initial value from config file 

例:

 string foo = Settings.Default.Foo; // Foo = "Foo" by default Settings.Default.Foo = "Boo"; Settings.Default.Save(); string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo" string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo" 

阅读“Windows 2.0 Forms Programming”,我偶然发现了这两种在这种情况下可能有用的有用方法:

ApplicationSettingsBase.Reload

ApplicationSettingsBase.Reset

来自MSDN:

重新加载与Reset形成对比,前者将加载最后一组保存的应用程序设置值,而后者将加载保存的默认值。

所以用法是:

 Properties.Settings.Default.Reset() Properties.Settings.Default.Reload() 

我不确定这是必要的,必须有一个更简洁的方式,否则希望有人发现这有用;

 public static class SettingsPropertyCollectionExtensions { public static T GetDefault(this SettingsPropertyCollection me, string property) { string val_string = (string)Settings.Default.Properties[property].DefaultValue; return (T)Convert.ChangeType(val_string, typeof(T)); } } 

用法;

 var setting = Settings.Default.Properties.GetDefault("MySetting"); 

Properties.Settings.Default.Reset()会将所有设置重置为其原始值。

我该如何回到Color.White?

你可以采取两种方式:

  • 在用户更改之前保存设置的副本。
  • 缓存用户修改的设置,并在应用程序关闭之前将其保存到Properties.Settings。

我通过2套设置解决了这个问题。 我使用Visual Studio默认为当前设置添加的那个,即Properties.Settings.Default 。 但我还在项目“项目 – >添加新项目 – >常规 – >设置文件”中添加了另一个设置文件,并将实际的默认值存储在那里,即Properties.DefaultSettings.Default

然后我确保我从不写入Properties.DefaultSettings.Default设置,只需从中读取即可。 将所有内容更改回默认值只是将当前值设置回默认值的情况。

我发现调用ApplicationSettingsBase.Reset会将设置重置为默认值,但同时也会保存它们。

我想要的行为是将它们重置为默认值但不保存它们(这样如果用户不喜欢默认值,那么在保存之前它们可以将它们还原)。

我写了一个适合我的目的的扩展方法:

 using System; using System.Configuration; namespace YourApplication.Extensions { public static class ExtensionsApplicationSettingsBase { public static void LoadDefaults(this ApplicationSettingsBase that) { foreach (SettingsProperty settingsProperty in that.Properties) { that[settingsProperty.Name] = Convert.ChangeType(settingsProperty.DefaultValue, settingsProperty.PropertyType); } } } }