Domanda

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 + "\"")
È stato utile?

Soluzione

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

Altri suggerimenti

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top