Is it possible to refer to the home directory in appSettings in the App.config file?

I have this C # project in Visual Studio (2010), and I would like to access the file in my home directory in the <appSettings> section of the App.config project file. That is, I use this syntax:

 <appSettings> <add key="Database" value="sqlite:///C:\Users\arvek\test.db3" /> </appSettings> 

Is it possible to refer to my home directory (C: \ Users \ arvek) via a variable instead of hard coding directly? F.ex .: value = "sqlite: /// $ HOME \ test.db3".

+6
source share
2 answers

ConfigurationManager will not automatically expand anything in the application settings, as these are just free-form strings, but you can do it manually. Use the ExpandEnvironmentVariables Environment method, which will expand the %VARIABLENAME% form variables to match the current environment. So:

 <appSettings> <add key="Database" value="sqlite:///%APPDATA%\database\test.db3" /> </appSettings> string path = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["Database"]); 

The root path to your home directory is in the% USERPROFILE% variable, although% APPDATA% is a traditional place to talk about what you are talking about. There is also% ALLUSERSPROFILE% for system-wide data (although on Windows 7, which actually points to a special system-wide data folder, not the "Public" profile.)

+9
source

It’s easier for me to simply get the application directory with this simple line of code

 string appBasePath = AppDomain.CurrentDomain.BaseDirectory; 

The way I always appeal to him.

0
source

Source: https://habr.com/ru/post/892495/


All Articles