0

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 + "\"")

2 Answers 2

3

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 + ""])
Sign up to request clarification or add additional context in comments.

3 Comments

You're missing a "]" in your last line.
+1 Showing not recommend, and even more credit for editing the original post. The AppSettings portion was setting off my OCD. :)
that worked I didn't even think to just stick it right in the brackets. Thought I needed the double quotes which caused me to have to escape them.
0

I don't know with keys, but for getting variables from the App.config file use better this way, the System.Configuration.ConfigurationManager.AppSettings is deprecated:

<applicationSettings>
  <nameOfNamespace.nameOfSettingsFile>
    <setting name="MAX_TRIES" serializeAs="String">
      <value>5</value>
    </setting>
  </nameOfNamespace.nameOfSettingsFile>
</applicationSettings>

You can create a .settings file in VS adding a new element to the project and choosing the settings file (its appearance is a gear) and create there the variables instead of in the App.config file.

Then you can use easily this:

int MAX_TRIES = nameOfNamespace.nameOfSettingsFile.Default.MAX_TRIES;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.