Search code examples
c#variablesweb-configapp-config

Variables within app.config/web.config


Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config. (I know I can manage all the concatenation in code, but I prefer it this way).


Solution

  • Good question.

    I don't think there is. I believe it would have been quite well known if there was an easy way, and I see that Microsoft is creating a mechanism in Visual Studio 2010 for deploying different configuration files for deployment and test.

    With that said, however; I have found that you in the ConnectionStrings section have a kind of placeholder called "|DataDirectory|". Maybe you could have a look at what's at work there...

    Here's a piece from machine.config showing it:

     <connectionStrings>
        <add
            name="LocalSqlServer"
            connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
            providerName="System.Data.SqlClient"
        />
     </connectionStrings>