Tech Blog‎ > ‎

VB.NET - Reading and writing app.config

posted Mar 14, 2014, 6:36 AM by Victor Zakharov   [ updated Mar 15, 2014, 7:14 PM ]
I found so many articles on the internet suggesting the need to write your own classes to read/write app.config.
While the read is fairly easy, people are struggling a lot with the write, some are saying that write is not supported by .NET at all.
There are numerous examples and training articles on how to get started with writing your own classes for that.

Well guess what - you don't need to write your own classes. If you are interested, continue reading.

According to MSDN, this approach should work for .NET 2.0+.
  1. Add reference to System.Configuration.dll.
  2. Add a class named AppConfig and paste below code into it:
Imports System.Configuration
Imports System.Reflection
Public Class AppConfig
 
  Private _config As Configuration
  Private _settings As AppSettingsSection 
  Public Function GetProperty(propertyName As StringAs String
    Return _settings.Settings.Item(propertyName).Value
  End Function
  Public Sub SetProperty(propertyName As String, propertyValue As String)
    _settings.Settings.Item(propertyName).Value = propertyValue
  End Sub 
  Public Sub New()     _config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location)     _settings = _config.AppSettings   End Sub   Protected Overrides Sub Finalize()     MyBase.Finalize()     _config.Save(ConfigurationSaveMode.Modified)   End Sub End Class

Usage is very simple - so this is just for completeness:

Dim _appConfig As New AppConfig

then

_appConfig.SetProperty(propertyName, propertyValue)

and

_appConfig.GetProperty(propertyName)

Settings will actually be saved when the variable _appConfig goes out of scope. So if you want immediate save, declare it at method level. This way AppConfig's destructor/Finalize will fire soon after method end. To defer saving until form exits, put at form class level. For application level, put it in some shared variable, and initialize in Sub Main, etc.

For my needs, a simple key/value collection in app.config was enough, so I did not go much further.
However, I found that ConfiguratonManager class supports working with multiple sections too (in case you need it).

If after reading all this, you still think own classes would be better, please feel free to send me an email and explain why you think so.
Logical and well argumented reasons will be published here as a side note. I can include a link to your blog or page as a credit. Thanks.