Search code examples
c#variablesconfigconfigurationmanagerappsettings

Retrieve values from config file based on variable


I have a c# application that uses a config file to access values. I'm looking to retrieve values from this config file based on the value of a variable.

Here is a config file:

<appsettings>
    <add key="1" value="10"/>
    <add key="2" value="20"/>
    <add key="3" value="30"/>
    <add key="4" value="40"/>
    <add key="5" value="40"/>
    <add key="6" value="60"/>
    <add key="7" value="70"/>
    <add key="8" value="80"/>
    <add key="9" value="90"/>
</appsettings>

I declared a variable in my program which represents the int of the day of the month.

int  intCurDay = DateTime.Now.Day;

trying to extract out the key that corresponds to the specific intCurDay, tried doing it two ways like so but can't figure it out.

int valueToUse = Convert.ToInt32(ConfigurationManager.AppSettings["{0}"],intCurDay)
int valueToUse = Convert.ToInt32(ConfigurationManager.AppSettings["\"" + intCurDay + "\"")

Solution

  • This should work:

    int valueToUse = Convert.ToInt32(ConfigurationManager.AppSettings[intCurDay.ToString()]);
    

    Other methods (not recommended - just so you see where your first attempts went wrong):

    int valueToUse = Convert.ToInt32(ConfigurationManager.AppSettings[string.Format("{0}",intCurDay)]);
    
    int valueToUse = Convert.ToInt32(ConfigurationManager.AppSettings["" + intCurDay + ""])