Search code examples
vb.netbasicmy.settings

Grabbing current user.config path (Visual Basic)


Is there a way of grabbing the location of the My.Settings user.config location? So for example I want to be able in VB to grab the path of the user.cofing file path to a string

The reason I ask is that I have an application where the user.config file is backed up and then restored, the issue is that with the my.settings folder structure it uses a unique hash with the folder name meaning that I cannot write into the code a static folder path, instead I need to be able to grab the location of the user.config OR be able to get the folder name of the application AppData.

Any ideas?

To put this in perspective, currently I'm using something like this:

Dim filePath As String

        filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\My_App\My_App.exe_Url_<the_hash_that_changes_causing_issues>\1.0.0.0\user.config"

Because of the hash change this will not always work


Solution

  • Try executing this code:

    Dim mainConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim userConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming)
    Dim userLocalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
    
    Console.WriteLine(mainConfig.FilePath)
    Console.WriteLine(userConfig.FilePath)
    Console.WriteLine(userLocalConfig.FilePath)
    

    You'll need to reference System.Configuration.dll and import System.Configuration.