13

I'd like to display the location of the user.config file in my windows forms application so a user can easily find it.

I understand how the path is created thanks to: Can I control the location of .NET user settings to avoid losing settings on application upgrade?.

However, in case this changes, I would rather not have to construct path this in my app, especially if there is an easy method for getting the user.config file location.

Community
  • 1
  • 1
Chris Weber
  • 5,555
  • 8
  • 44
  • 52

3 Answers3

26

Try this:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);

MessageBox.Show(config.FilePath);
Francis
  • 3,335
  • 20
  • 46
  • 3
    That is exactly what I need. Any idea what the real difference between ConfigurationUserLevel.PerUserRoamingAndLocal and ConfigurationUserLevel.PerUserRoaming is? RoamindAndLocal would seem to cover both situations??? – Chris Weber Jan 27 '12 at 21:18
  • 2
    To get the local Configuration object that applies to the current user, set userLevel to PerUserRoamingAndLocal. To get the roaming Configuration object that applies to the current user, set userLevel to PerUserRoaming. – Hady Allam Jul 11 '16 at 15:43
  • 2
    If you find that `ConfigurationManager` is not present in your application you may need to include the System.Configuration.dll assembly and a using statement of `using System.Configuration;` More in [this stackoverflow answer.](https://stackoverflow.com/questions/1796851/unable-to-access-configurationmanager-appsettings-in-a-windows-forms-application) – Steve Lautenschlager Jun 14 '18 at 19:25
  • 1
    Downvoting. This answer lacks proper imports. Symbols used in this answer do not show in the IDE. – Tomáš Zato Sep 05 '18 at 11:32
  • Maybe I'm missing something but this doesn't seem to answer the question. I have the same problem, I want to know, in my program, at run time, exactly which file my program is getting its settings from. This gives me three options, so which is it? – Dave May 09 '20 at 16:41
  • What do you mean by 3 options? `ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath` is 1 string, and it points directly towards the `user.config` file - including the SHA1 hash portion. – radj307 May 21 '22 at 02:02
8

Depending on how your application runs, ConfigurationUserLevel.PerUserRoamingAndLocal may be the property you're looking for rather than ConfigurationUserLevel.PerUserRoaming;

i.e:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
MessageBox.Show(config.FilePath);

Be sure to have System.Configuration in your project's references in order to use this.

c0g
  • 2,665
  • 1
  • 13
  • 5
2

Use the ConfigurationManager to get the Configuration-object. The Configuration-object has a string property FilePath. See: Configuration-Members

Mithrandir
  • 24,869
  • 6
  • 50
  • 66