VB, get configuration from different configuration file
Asked Answered
I

0

1

In visual studio I have solution with 3 projects in it. Project 1 must use configuration file which belongs to project 2. Normally, to access current project configuration file, code below must be used:

Private ReadOnly appSettings As Object = ConfigurationManager.AppSettings
Console.WriteLine(appSettings("myValue"))

What if we need to access configuration file which belongs to different project? Example below:

For solution many thanks to "RBT" who gave his code:

Link to solution

I modified it a bit to make it work in VB:

Public Function CustomConfig(value As String, Optional ByVal CustomConfigName As String = "MyCustomSettings.exe.config")
    Dim configFileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap()
    configFileMap.ExeConfigFilename = CustomConfigName
    Dim configFile = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None)
    Dim section As AppSettingsSection = CType(configFile.GetSection("appSettings"), AppSettingsSection)
    Dim keyValueConfigElement As String = section.Settings(value).Value

    Return keyValueConfigElement
End Function

Usage:

Console.WriteLine(CustomConfig("myValueInConfigFile"))
Iconography answered 6/4, 2019 at 9:41 Comment(9)
What you are suggesting is probably not the case. What is the relationship between the projects? Is there one application and two libraries? Three applications?Bioastronautics
Project 1 is Console app which just prints info, Project 2 is Windows Forms App which has important configuration. So I need to use configuration from Project 2 in Project 1Iconography
ConfigurationManager.OpenExeConfiguration Method.Bioastronautics
Could you please point me to the right direction and show example how exactly it must be used?Iconography
I did point you in the right direction by providing a link. If you want information or examples beyond what the documentation I linked to provides, that what search engines are for.Bioastronautics
Thanks for your effort, but the problem is that there is no exact explanation on how to achieve this. Everyone just tell that ConfigurationManager.OpenExeConfiguration should be used, but no one gives example :DIconography
ConfigurationManager.OpenExeConfiguration Method returns KeyValueConfigurationCollection instead of KeyValueInternalCollection So I am not able to access configuration file data. Who can help?Iconography
I would encourage you to add your final answer as an answer to this thread rather as an update in the question. It'll make the thread look complete whomsoever visits your question in future.Elconin
RBT - Thank you, I edited my post which explains solution. Happy coding ;)Iconography

© 2022 - 2024 — McMap. All rights reserved.