slolife
slolife

Reputation: 19870

How to open a file formatted as a .NET config file to get a System.Configuration.Configuration object

I am in an ASP.NET app and I want to open a file, formatted similar to web.config or one of config files that you can link it to (appSettings, pages, etc.) and get the appSettings

Dim filePath As String = HostingEnvironment.MapPath("~/developer.config")
If (File.Exists(filePath)) Then
   Dim map As New WebConfigurationFileMap()
   map.MachineConfigFilename = filePath
   Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(map, "/")
   Dim developerAppSettings As AppSettingsSection = config.AppSettings
   Return developerAppSettings
Else
   Return Nothing
End If

I'd like developerAppSettings to be set to the appSettings section of my developer.config file, which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<appSettings>
    <add key="CustomerLogosFolder" value="C:\code\ExactBidTFS\RIMS\Development\CustomerLogos" />
</appSettings>

Apparently, I am not using OpenMappedWebConfiguration() correctly because it gives me an ArgumentOutOfRange exception (it appears to be the second, "/" parameter).

Is this even possible to do? I've tried OpenWebConfiguration() as well, but there seems to be some confusion as to what the file path parameter is used for in that situation. My experiments show that the file path is just a virtual directory that contains the web.config, not to specify my own developer.config file.

Upvotes: 1

Views: 162

Answers (1)

Patelos
Patelos

Reputation: 23

I saw this question while I was trying to look for a way to open my web app's config file from a console app. I also saw the post here that helped me.

I know it's an old question but I figured I might as well post my solution here.

I wrote the following snippet, which worked for me:

Dim map As New ExeConfigurationFileMap()
Dim filePath As String = "c:\temp\developer.config"
map.ExeConfigFilename = filePath
Dim configFile As Configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None)
If configFile IsNot Nothing Then
  Dim myAppSection As AppSettingsSection = TryCast(configFile.GetSection("appSettings"), AppSettingsSection)
  Debug.Print(myAppSection.Settings("CustomerLogosFolder").Value)
End If

I also modified the xml a bit as below to make it similar to other config files:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="CustomerLogosFolder" value="C:\code\ExactBidTFS\RIMS\Development\CustomerLogos" />
    </appSettings>
</configuration>

At the end of the execution I got "C:\code\ExactBidTFS\RIMS\Development\CustomerLogos" in my Immediate Window

Upvotes: 1

Related Questions