0

I want to save some of my programs variables to a config.file. So, I try to use "AppConfig ", as that almost seems to be the standard. Before trying anything complicated, I put it to the test in a; as simple as possible program. (and a variety of variations) But I keep getting this error:System.NullReferenceException: 'Object reference not set to an instance of an object.' (Visual Basic)(Visual Studio 2022) (Net.6) In the line: _settings.Settings.Item(propertyName).Value = propertyValue As per instruction I referenced :System.Configuration, And imported System.Configuration and System.Reflection I try to save one variable "atest" and its data "bey". So, why doesn't this work? All the code:

Imports System.Configuration
Imports System.Reflection
Public Class Form1
    Sub New()
        Dim test As String = "bey"
        ' This call is required by the designer.
        InitializeComponent()
        Dim _appConfig As New AppConfig
        _appConfig.SetProperty("test", "dd")
    End Sub
End Class
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

Thanks in advance for any help...

I will probably feel very stupid if the solution is very simple...

P.S. The code is almost literary all from this Blog..


Update 1!

I did a U-turn as I found that there is an in-build function

that would be even more simple.

That resulted in more errors..

But eventually lead to half a solution.

Please change channels to that thread, as this one seems to be redundant.

Jhonny Q
  • 11
  • 4
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ken White Apr 14 '22 at 02:01
  • You seem to have left out most of the code of that `AppConfig` class but you haven't shown anywhere that you've actually assigned anything to the `_settings` field. – user18387401 Apr 14 '22 at 02:44
  • Yes, sorry... too long a night, not enough coffee. – Jhonny Q Apr 14 '22 at 12:59

0 Answers0