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

2 回答 2

3

这应该有效:

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

其他方法(不推荐 - 只是为了让您了解第一次尝试出错的地方):

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

int valueToUse = Convert.ToInt32(ConfigurationManager.AppSettings["" + intCurDay + ""])
于 2013-08-06T17:52:11.660 回答
0

我不知道键,但是为了从App.config文件中获取变量更好地使用这种方式,System.Configuration.ConfigurationManager.AppSettings不推荐使用:

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

您可以在 VS 中创建一个 .settings 文件,向项目添加一个新元素并选择设置文件(它的外观是一个齿轮)并在那里创建变量而不是在App.config文件中。

然后你可以很容易地使用这个:

int MAX_TRIES = nameOfNamespace.nameOfSettingsFile.Default.MAX_TRIES;
于 2014-07-24T11:40:51.027 回答