Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 957
aknuds1 Avatar asked Jul 11 '11 13:07

aknuds1


1 Answers

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.)

like image 86
Michael Edenfield Avatar answered Sep 18 '22 02:09

Michael Edenfield