10

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

Michael M.
  • 6,561
  • 1
  • 16
  • 18

2 Answers2

5

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

Christian Hayter
  • 30,581
  • 6
  • 72
  • 99
  • Thanks. I think that user of application need read and write permissions only. If I'm wrong, please correct me. – Michael M. Mar 23 '10 at 17:57
  • 1
    To clarify: the `app.config` file is installed into a folder underneath Program Files. By default this is set up to not allow write access to standard users. Although .NET will happily allow you to write to any `.config` file via the normal Configuration API, if you actually try it running as a standard user then you will get a security exception. – Christian Hayter Mar 23 '10 at 18:35
  • Thanks. I'll remember this. I'll use oportunity for writing into app.config for my windows services not for desktop application. – Michael M. Mar 23 '10 at 20:04
4

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.

Pike65
  • 562
  • 2
  • 6