This page looks best with JavaScript enabled

VB.NET - Reading and writing app.config

 ·   ·  ☕ 2 min read

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:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Imports System.Configuration
Imports System.Reflection
Public Class AppConfig
  Private _config As Configuration
  Private _settings As AppSettingsSection 

  Public Function GetProperty(propertyName As String) As 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:

1
Dim _appConfig As New AppConfig

then

1
_appConfig.SetProperty(propertyName, propertyValue)

and

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


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)