这是允许您更改条目的方法<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的输出窗口中显示异常,但将继续执行代码。
注意(对类似主题的交叉引用):
applicationSettings部分不同,因为它区分“用户”和“应用程序”范围,并且支持不同的数据类型,而不仅仅是字符串。如果您想知道如何处理applicationSettings,可以在此处找到它(在 stackoverflow 上):
如何访问applicationSettings
如果您不确定是否应该使用AppSettings
or applicationSettings
,请在决定之前阅读此内容。
如果您遇到警告'ConfigurationSettings.AppSettings' is obsolete
,那么此提示可以帮助您。
如果您使用的是.NET Core框架,请查看此链接:.NET Core 中的 AppSettings