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

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

I have a second application that should read a parameter from this file.

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

I think I could create a path manually from

[Application.LocalUserAppDataPath] [Company Name] [AppName + some kind of landmark] [application version]

but it seems hacked.

+5
source share
3 answers

The logic for creating the path to the place where the user configuration file lives is usually embedded in the application, especially the parts

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

, .

, DLL , ​​

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;
}

.

+1

, . , . , . , ? , . , , . , .

0

ConfigurationManager Configuration, :

Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
string userConfigFilePath = cfg.FileName;

Please note that you can use different ConfigurationUserLevel values ​​to go to global, local or roaming settings.

Edit: The version of OpenExeConfiguration (), which takes the exe file name as an argument, gives access only to the application configuration file, and not to the user configuration.

0
source

All Articles