C# 如何更改运行时应用程序设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/546229/
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 to change in runtime application settings
提问by rpf
I'm trying to change in runtime one key of my applications settings file, but it does not work.
我试图在运行时更改我的应用程序设置文件的一个键,但它不起作用。
I do on that way:
我这样做:
ConfigurationSettings.AppSettings["XPTO"] = "HELLO";
It seems that it only changes in memory, not on the file.
似乎它只在内存中更改,而不是在文件中更改。
Does anyone knows how to do this?
有谁知道如何做到这一点?
Thanks.
谢谢。
采纳答案by el2iot2
Take a look at my overview of .NET settings files...In short, I think you want a user-scoped setting. It will behave more like you expect.
看看我对 .NET 设置文件的概述……简而言之,我认为您需要一个用户范围的设置。它将表现得更像您期望的那样。
Edit:If you are using the settings designer in Visual Studio, then simply change the "Scope" to "User". If not, you should be able to do the equivalent programmatically.
编辑:如果您在 Visual Studio中使用设置设计器,那么只需将“范围”更改为“用户”。如果没有,您应该能够以编程方式执行等效操作。
回答by brendan
The AppSettings file is not designed to be writable. It is designed to store configurations that will not change at run time but might change over time ie: DB Connection Strings, web service URL's, etc.
AppSettings 文件不是可写的。它旨在存储在运行时不会更改但可能会随时间更改的配置,即:数据库连接字符串、Web 服务 URL 等。
So, while it may be possible to update the file in reality you should re-asses if this value should be stored there.
因此,虽然实际上可以更新文件,但您应该重新评估该值是否应该存储在那里。
回答by Joe
Assuming your app has write permissions on the file...
假设您的应用程序对该文件具有写入权限...
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // the config that applies to all users
AppSettingsSection appSettings = config.AppSettings;
if (appSettings.IsReadOnly() == false)
{
appSettings("Key").Value = "new value";
config.Save();
}
I'm ignoring all the possible exceptions that can be thrown...
我忽略了所有可能抛出的异常......