NoC*_*nce 4 .net c# application-settings winforms
我有一个名为的属性,它是通过 Visual Studio 中的属性设置窗口 A设置的值(项目 \xe2\x86\x92 属性 \xe2\x86\x92 设置)。AAA
A我可以使用此循环获取该属性的原始值。
\n如果我更改该值,也就是说NewValue,我可以使用以下代码获取新值:
Properties.Settings.Default.A\nRun Code Online (Sandbox Code Playgroud)\n\n但是,在循环内,我不知道如何在不使用语法的情况下获取当前属性值:
\n\nProperties.Settings.Default.VariableName\nRun Code Online (Sandbox Code Playgroud)\n\n例如:
\n\nProperties.Settings.Default.A= "NewValue";\nProperties.Settings.Default.Save();\nforeach (SettingsProperty _currentProperty in Properties.Settings.Default.Properties)\n{\n Console.WriteLine(_currentProperty.Name + "," + _currentProperty.DefaultValue.ToString());\n}\nRun Code Online (Sandbox Code Playgroud)\n\n上面的循环显示了属性的原始值(旧的默认值是AAA)。
我已检查该user.config文件并确保它正在显示NewValue。
我假设必须有某种方法使用我不知道的属性或方法来引用当前值(也许我应该迭代另一个集合?)。
\n\n问题是,如何在foreach上面的循环中显示这个新值?
查询SettingsProvider时,当前值在SettingsPropertyValueCollectionProperties.Settings类中返回(如果没有为设置定义提供程序,则使用默认提供程序LocalFileSettingsProvider )。
当前代码正在修改设置的值,然后在将设置保存到本地存储后检查这些值。
该代码迭代该Properties.Settings.Default.Properties集合,对应于ApplicationSettingsBase.Properties属性,这是一个SettingsPropertyCollection集合,其中包含SettingsProperty对象,在内部用于表示配置属性的元数据。
该类只能返回关联设置的默认值。
要检查与 Properties Settings 关联的当前值,代码应改为迭代上述SettingsPropertyValueCollection由 ApplicationSettingsBase.PropertyValues属性返回的值,该属性枚举 SettingsPropertyValue对象。这些对象的PropertyValue
属性返回当前分配给设置的运行时值。
要返回当前值,可以将代码修改为:
foreach (SettingsPropertyValue prop in Properties.Settings.Default.PropertyValues) {
Console.WriteLine($"{prop.Name} -> {prop.PropertyValue}");
}
Run Code Online (Sandbox Code Playgroud)
关于应用程序设置的一些注意事项:
应用程序设置分为 2 个主要类别:
应用程序设置(范围内的设置Application)
只读,没有关联本地存储,因此无法在运行时更改。这些设置存储在文件中,在构建项目时app.config复制到文件中。[Application].exe.config
用户设置(范围内的设置User)(适用于 Visual Studio 2017+)
这些设置与应用程序设置一起存储,但具有关联的本地存储文件,用于存储用户(或应用程序)可以在运行时更改的值time:
2.1user.config存储在当前用户配置文件中的文件
[User]/AppData/Local/[CompanyName]/[ProductName].exe_<hash>/[Assembly Version]
Run Code Online (Sandbox Code Playgroud)
部分,如果设置的Roaming属性设置为false.
2.2user.config存储在当前用户配置文件中的文件
[User]/AppData/Roaming/[CompanyName]/[ProductName]/[File Version]
Run Code Online (Sandbox Code Playgroud)
部分,如果设置Roaming属性设置true为相反。
User当将新值分配给设置时,范围内设置的原始值(即Default值)不会被修改。
用户范围中的设置可以使用ApplicationSettingsBase.Save()方法保存在运行时分配的新值:
Properties.Settings.Default.Save();
Run Code Online (Sandbox Code Playgroud)
应用程序可以使用ApplicationSettingsBase.Reload()方法重新加载最后保存的值(可能会放弃最近的更改):
Properties.Settings.Default.Reload();
Run Code Online (Sandbox Code Playgroud)
要放弃对用户设置所做的所有更改,可以使用ApplicationSettingsBase.Reset()方法将设置重置为默认值:
Properties.Settings.Default.Reset();
Run Code Online (Sandbox Code Playgroud)