.net 如何在不使用用户设置的情况下在运行时读取/写入 app.config 设置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3638754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read/write app.config settings at runtime without using user settings?
提问by Tim Santeford
I'm looking for a way to store application or machine level settings that can be written to at runtime using Application Settings. User settings allow read/write but application settings do not. I have been using user settings for saving settings like this at runtime but this has really proven to be impractical for the following reasons:
我正在寻找一种方法来存储可以在运行时使用Application Settings写入的应用程序或机器级设置。用户设置允许读/写,但应用程序设置不允许。我一直在使用用户设置在运行时保存这样的设置,但由于以下原因,这确实被证明是不切实际的:
- All users of the machine need to share settings.
- In support calls (especially in crisis situations) it is difficult to explain to users/employees where to find and modify these settings manually (appdata is a hidden folder among other things).
- New versions of the app need to use previous settings (user settings seem to get blown away with new versions).
- It is common for our employees to copy the application to a new folder which also resets the user settings.
- 机器的所有用户都需要共享设置。
- 在支持电话中(尤其是在危机情况下),很难向用户/员工解释在哪里可以手动查找和修改这些设置(appdata 是一个隐藏文件夹等)。
- 应用程序的新版本需要使用以前的设置(用户设置似乎被新版本吹走了)。
- 我们的员工通常会将应用程序复制到一个新文件夹,该文件夹也会重置用户设置。
Our company machines are only used by one user anyway so user specific settings are not generally needed.
我们公司的机器只供一名用户使用,因此通常不需要用户特定的设置。
Otherwise I really like using application settings and would like to continue to use them if possible. It would be ideal if the settings could reside in the same folder as the EXE(like good ol' ini files once did).
否则我真的很喜欢使用应用程序设置,如果可能的话,我想继续使用它们。如果设置可以驻留在与 EXE 相同的文件夹中(就像曾经做过的好 ol' ini 文件),那将是理想的。
NOTE:This is a WPF application and not an ASP.net web app so no web.config.
注意:这是一个 WPF 应用程序,而不是 ASP.net Web 应用程序,因此没有 web.config。
采纳答案by Task
Well, I haven't yet wanted to change application settings at runtime (that's what I use user settings for), but what I have been able to do is write application settings at install time. I imagine that a similar approach might work at runtime. You could try it out since there don't seem to be any other propsed solutions ATM.
好吧,我还不想在运行时更改应用程序设置(这就是我使用用户设置的目的),但我能够做的是在安装时编写应用程序设置。我想类似的方法可能会在运行时起作用。您可以尝试一下,因为似乎没有任何其他建议的解决方案 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();
Hope that helps!
希望有帮助!
回答by Matt
This is the method which allows you to change entries in the <AppSettings>:
这是允许您更改以下条目的方法<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
Notethat I have found it is necessary to refresh the section appSettingsafter the update.
请注意,我发现有必要在更新appSettings后刷新该部分。
The function removes a key before it adds it to avoid double entries. This works also if the key does not previously exist. If there is any error it returns false, on success true. The method to read settings is trivial and just listed for completeness:
该函数在添加键之前删除键以避免重复输入。如果密钥以前不存在,这也适用。如果有任何错误,则返回false,成功则返回true。读取设置的方法很简单,只是为了完整性而列出:
internal static string GetSetting(string Key)
{
string result = null;
try
{
result = ConfigurationManager.AppSettings[Key];
}
finally
{ }
return result;
} // function
Notethat I've surrounded it by a try ... finallyblock to suppress errors. If any errors occur, then GetSetting simply returns null while SetSetting returns false. That makes handling easier, however if you require the exceptions you can still add
请注意,我用try ... finally块包围它以抑制错误。如果发生任何错误,则 GetSetting 仅返回 null,而 SetSetting 返回 false。这使得处理更容易,但是如果您需要例外,您仍然可以添加
catch (Exception) { throw; }
to throw the exception up to the caller. Or, for debugging you could add:
将异常抛出给调用者。或者,为了调试,您可以添加:
#if DEBUG
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
Which will show the exception in the Outputwindow of Visual Studio if you have selected the "Debug" configuration, but will continue with the code.
如果您选择了“调试”配置,它将在 Visual Studio的输出窗口中显示异常,但将继续执行代码。
Note (cross-reference to a similar topic):
注意(交叉引用类似主题):
The applicationSettingssection is different, since it distinguishes between "User" and "Application" scope and it supports different datatypes, not just strings. If you want to know how you can handle applicationSettings, you can find it here (on stackoverflow):
How to access applicationSettingsIf you are uncertain whether you should use
AppSettingsorapplicationSettings, then read thisbefore you decide it.If you encounter the warning
'ConfigurationSettings.AppSettings' is obsolete, then this hint can help you.If you're using the .NET Coreframework, check out this link: AppSettings in .NET Core
该的applicationSettings部分是不同的,因为它区分了“用户”和“应用程序”范围之间,它支持不同的数据类型,而不只是字符串。如果您想知道如何处理applicationSettings,可以在此处(在 stackoverflow 上)找到它:
如何访问applicationSettings如果您遇到警告
'ConfigurationSettings.AppSettings' is obsolete,那么此提示可以帮助您。如果您使用的是.NET Core框架,请查看此链接:.NET Core 中的 AppSettings
回答by Dillie-O
WPF applications are able to access the app.config file just like WinForms apps through the
WPF 应用程序能够像 WinForms 应用程序一样通过
ConfigurationManager.OpenExeConfiguration()
method. The trick is to have the values you want to access in the AppSettings tag of your App.config file (also available in WPF applications).
方法。诀窍是在 App.config 文件的 AppSettings 标记中包含要访问的值(也可在 WPF 应用程序中使用)。
The trick to all of this is to make sure to call the following methods when you're done modifying your properties:
所有这一切的诀窍是确保在完成修改属性后调用以下方法:
MyConfig.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
I wrote a complete "how to" on this a little while back that explains it all here.
不久前我写了一个完整的“如何做”,在这里解释了这一切。

