Writing custom sections into app.config

2020-02-10 21:46发布

问题:

I want to save some custom data into application configuration file and I need to create some custom sections in app.config. Reading custom data from app.config is simple task, but I can't write information from my programm into app.config. For finding solution of this problem I create test project.

For reading data from custom section app.config I used information from this article:

http://devlicio.us/blogs/derik_whittaker/archive/2006/11/13/app-config-and-custom-configuration-sections.aspx

回答1:

First override IsReadyOnly() in your CustomConfigSection to return false.

Once you've done that you should be able to do something like this (this is for ASP.NET, but it might be transferably):

System.Configuration.Configuration configFile = WebConfigurationManager.OpenWebConfiguration("~");
CustomConfigSection config = (CustomConfigSection)configFile.GetSection("Custom");
config.Tweak = 1;
config.Change = "foo";
configFile.Save();

Give that a try.



回答2:

You really ought not to write anything to app.config, because if you do then you are limiting use of your app to Administrators only. It's better practice to write settings to a separate .config file located in a user profile folder, e.g. <profiles>\<user name>\Application Data\<your product name>.