Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the location of the user.config file of any .net application

I have a main application that saves settings to a user.config file.

I have a second app that needs to read a setting from this file.

Is there a simple/elegant way to get the location of the user.config file of the main app?

I guess i could build up the path manually from

[Application.LocalUserAppDataPath][CompanyName][AppName + some sort of guid][App version]

but that seems mightily hacky.

like image 899
Keith Cassidy Avatar asked Nov 15 '22 02:11

Keith Cassidy


1 Answers

The logic for creating a path to the place where the user configuration file lives is typically build into the application, escpecially the parts

[CompanyName][AppName + some sort of guid][App version]

so there is not general way to ask the framework where the user config is stored.

However, we solved this issue for our program system by providing a common DLL for all apps containing a function like this

static Configuration GetMainConfig()
{
    string mainPgmConfigDir = GetMainProgramConfigDir();
    ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
    configFile.ExeConfigFilename = Path.Combine(mainPgmConfigDir, "user.config");
    return ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
}

static string GetMainProgramConfigDir()
{
    string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    string companyDir = Path.Combine(appDataDir, VersionInfo.Company);
    string productDir = Path.Combine(companyDir, "yourProgramName");
    string versionDir = Path.Combine(productDir, "yourVersionNumber");
    return versionDir;
}

This function gets you the same user configuration for all of your applications.

like image 99
Doc Brown Avatar answered Dec 22 '22 09:12

Doc Brown