我正在寻找一种存储应用程序或机器级别设置的方法,这些设置可以在运行时使用 Application Settings 写入。用户设置允许读/写,但应用程序设置不允许。我一直在使用用户设置来在运行时保存这样的设置,但由于以下原因,这确实被证明是不切实际的:
我们公司的机器只能由一个用户使用,因此通常不需要用户特定设置。
否则我真的很喜欢使用应用程序设置,如果可能的话我想继续使用它们。如果设置可以驻留在 与 EXE 相同的文件夹中(就像曾经的好 ol'ini 文件一样),那将是理想的。
注意:这是一个 WPF 应用程序,而不是 ASP.net web 应用程序,因此没有 web.config。
好吧,我还不想在运行时更改应用程序设置(这就是我使用用户设置的目的),但我能够做的是在安装时编写应用程序设置。我想类似的方法可能会在运行时起作用。您可以尝试一下,因为似乎没有任何其他推荐的 ATM 解决方案。
exePath = Path.Combine( exePath, "MyApp.exe" );
Configuration config = ConfigurationManager.OpenExeConfiguration( exePath );
var setting = config.AppSettings.Settings[SettingKey];
if (setting != null)
{
setting.Value = newValue;
}
else
{
config.AppSettings.Settings.Add( SettingKey, newValue);
}
config.Save();
希望有帮助!
这是一种允许您更改条目的方法
<AppSettings>
:
internal static bool SetSetting(string Key, string Value)
{
bool result = false;
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(Key);
var kvElem= new KeyValueConfigurationElement(Key, Value);
config.AppSettings.Settings.Add(kvElem);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
result = true;
}
finally
{ }
return result;
} // function
注意我发现有必要在更新后刷新
appSettings
部分
该函数在添加键之前删除键以避免重复输入。如果密钥以前不存在,这也适用。如果有任何错误,它返回 false,成功则返回 true。读取设置的方法很简单,只是为了完整性而列出:
internal static string GetSetting(string Key)
{
string result = null;
try
{
result = ConfigurationManager.AppSettings[Key];
}
finally
{ }
return result;
} // function
注意我用try ... finally块包围它以抑制错误。如果发生任何错误,则 GetSetting 仅返回 null,而 SetSetting 返回 false。这使处理更容易,但是如果您需要例外,您仍然可以添加
catch (Exception) { throw; }
将异常抛给调用者。或者,为了调试,您可以添加:
#if DEBUG
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
如果您选择了“调试”配置,它将在 Visual Studio 的Output 窗口中显示异常,但将继续代码。
注意(对类似主题的交叉引用):
applicationSettings 部分不同,因为它区分“用户”和“应用程序”范围,并且它支持不同的数据类型,而不仅仅是字符串。如果您想知道如何处理 applicationSettings,您可以在这里(在 stackoverflow 上)找到它:
如何访问应用程序设置
如果你不确定你应该使用
AppSettings
还是applicationSettings
,那么在你决定之前阅读这个。
如果遇到警告
'ConfigurationSettings.AppSettings' is obsolete
,那么这个提示可以帮到你
如果您使用的是 .NET Core 框架,请查看此链接:.NET Core 中的 AppSettings
更多信息:
WPF 应用程序能够像 WinForms 应用程序一样通过
访问 app.config 文件ConfigurationManager.OpenExeConfiguration()
方法。诀窍是在 App.config 文件的 AppSettings 标记中获取您想要访问的值(在 WPF 应用程序中也可用)。
所有这些的诀窍是确保在完成修改属性后调用以下方法:
MyConfig.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
我不久前写了一个完整的“操作方法”来解释这一切here.