0

I am working on a project that requires me to modify the .config file for a Windows service (written in ASP.NET) I wrote. The changes need to be made from an administrative website I am developing. When the user selects the 'UPDATE' button on the web app, the code below is executed:

Protected Sub ModifyAppConfig()
        Try
            Dim configFile = "C:\App\App.exe.config"
            Dim configFileMap As New ExeConfigurationFileMap
            configFileMap.ExeConfigFilename = configFile
            Dim config As System.Configuration.Configuration
            config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)
            config.AppSettings.Settings("LogDirectory").Value = txtLogDirectory.Text '* EXCEPTION IS THROWN HERE *
            config.Save()
        Catch ex As Exception

        End Try
    End Sub

When the application is trying to access "LogDirectory" AppSettings index, an exception is thrown. Object reference not set to an instance of an object. During debugging, the AppSettings.Count = 0. How come none of the AppSettings are imported?

I know that it is correctly opening the file because there are ConnectionString data. Below is the config File:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <connectionStrings>
      <add name="conn" connectionString="Data Source=DBASE;Initial Catalog=NGDevl;Integrated Security=True" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
    </startup>
    <appSettings>
      <add key="LogDirectory" value="C:\CTemp\"/>
    </appSettings>
</configuration>

How can I access and modify the AppSettings("LogDirectory") value?

Peter Sun
  • 1,675
  • 4
  • 27
  • 50
  • It sounds like maybe your app.config wasn't updated? 1) Is this an "app.config" ... or "something else"? 2) Is the executable a .Net .dll or .exe, and exactly how/where is it deployed on your filesystem? 3) Is the app.config *IN THAT PATH* correct? 4) Let's say your dll is "MyService.dll". Is there a corresponding "MyService.dll.config" in that directory? Does it have the correct "add key" in "appSettings"? – paulsm4 Mar 10 '19 at 20:21
  • This is .net windows service. The file is app.exe.config. The path is correct. – Peter Sun Mar 10 '19 at 20:23
  • Q: Does it have the correct "add key" in "appSettings"? Q: What happens if you add the line `Dim currentLogDir = config.AppSettings.Settings("LogDirectory")`? Is it "Nothing"? If not, does it have a "Value" property? – paulsm4 Mar 10 '19 at 20:30
  • returns nothing (null) – Peter Sun Mar 10 '19 at 20:38
  • OK: Your app.config syntax is correct, your filepath is correct, and your "open" appears to be succeeding. 1) Consider if [ConfigurationUserLevel.None](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationuserlevel?redirectedfrom=MSDN&view=netframework-4.7.2) might be causing grief. 2) Verify you can read *anything* from the [Configuration](https://nicolaspeters.wordpress.com/tag/openmappedexeconfiguration/) config object you've opened. – paulsm4 Mar 10 '19 at 20:54
  • See also [Get the App.Config of another Exe](https://stackoverflow.com/a/53553/421195) – paulsm4 Mar 10 '19 at 21:01

1 Answers1

0

Frankly, I don't see anything wrong with your program.

I've created a VB.Net/Console mode MCVE that might help your troubleshooting

Module1.vb

Imports System.Configuration

'
' EXAMPLE OUTPUT:
'   Reading config file(test.exe.config)...
'   config.AppSettings.Settings("LogDirectory") : C : \CTemp\
'   connectionStrings: <connectionStrings>
'   <add name = "conn" connectionString="Data Source=DBASE;Initial Catalog=NGDevl;
'   Integrated Security=True" providerName="System.Data.SqlClient"/>
'     </connectionStrings>
'   appSettings: <appSettings>
'   <add key = "LogDirectory" value="C:\CTemp\"/>
'     </appSettings>
'   startup: <startup>
'   <supportedRuntime version = "v4.0" sku=".NETFramework,Version=v4.5"/>
'     </startup>
'   3 sections were found.
'
Module Module1

    Sub Main()
        ' Get filename
        Dim args() As String = System.Environment.GetCommandLineArgs()
        If args.Length <> 2 Then
            Console.WriteLine("USAGE: ReadAppConfig <\path\to\app.config>")
            Return
        End If
        Dim configFilePath As String = args(1)

        ' Open config file
        Try
            Console.WriteLine("Reading config file(" & configFilePath & ")...")
            Dim configFileMap As New ExeConfigurationFileMap
            configFileMap.ExeConfigFilename = configFilePath
            Dim config As System.Configuration.Configuration
            config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)

            ' Try to read AppSettings["LogDirectory"]
            Dim obj = config.AppSettings.Settings("LogDirectory")
            If IsNothing(obj) Then
                Console.WriteLine("config.AppSettings.Settings(""LogDirectory""): NULL")
            Else
                Console.WriteLine("config.AppSettings.Settings(""LogDirectory""): " & obj.Value)
            End If

            ' Dump all Sections
            Dim ct As Integer = 0
            For Each section As ConfigurationSection In config.Sections
                Dim xml = section.SectionInformation.GetRawXml
                If Not xml = Nothing Then
                    Console.WriteLine(section.SectionInformation.Name & ": " & xml)
                    ct = ct + 1
                End If
            Next
            Console.WriteLine(ct & " sections were found.")
        Catch ex As Exception
            System.Console.WriteLine("ERROR:   " & ex.Message)
        End Try

    End Sub

End Module

test.exe.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="conn" connectionString="Data Source=DBASE;Initial Catalog=NGDevl;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <appSettings>
    <add key="LogDirectory" value="C:\CTemp\"/>
  </appSettings>
</configuration>
  • Project > test.exe.config: I set the "Copy to Output" property to "Copy if Newer"

  • Project > Properties > Debug: I set "Command line arguments" to "test.exe.config"

'Hope that helps...

paulsm4
  • 114,292
  • 17
  • 138
  • 190