Is it possible to refer to home directory within appSettings in an App.config file?
I开发者_如何学Go 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.)
I find it easier to just get the app's directory with this simple line of code
string appBasePath = AppDomain.CurrentDomain.BaseDirectory;
That's how I always refer to it.
精彩评论