I have this C# project in Visual Studio (2010), and I'd like to refer to a file in my home directory in the <appSettings>
section of the project's App.config 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 hardcoding it directly? F.ex.: value="sqlite:///$HOME\test.db3".
The ConfigurationManager
won't automatically expand anything in the app settings, since they are just free-form strings, but you can do so manually. Use the ExpandEnvironmentVariables
method of Environment
, which will expand variables of the form %VARIABLENAME%
according to 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, though %APPDATA% is the traditional place to put the kind of thing you're talking about. There is also %ALLUSERSPROFILE% for system-wide data (though in Windows 7 that actuallypoints to a special system-wide data folder, not the "Public" profile.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With