How to change in runtime application settings

旧时模样 提交于 2019-12-30 23:34:20

问题


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.


回答1:


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.

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.




回答2:


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.

So, while it may be possible to update the file in reality you should re-asses if this value should be stored there.




回答3:


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...



来源:https://stackoverflow.com/questions/546229/how-to-change-in-runtime-application-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!