【问题标题】:Declare variables in app.config for consuming inside app.config在 app.config 中声明变量以便在 app.config 中使用
【发布时间】:2017-05-07 00:03:43
【问题描述】:

我有一个 app.config 文件,其中我在该文件中有很多次相同的值,并且希望能够在一个地方更改它。

类似:

<appSettings>
    <add key="dbHostAddress" value="localhost" />
</appSettings>

然后将它用于我的连接字符串中的数据源值,如下所示

<connectionStrings><add name="ConnectionString" connectionString="Data Source=I WOULD LIKE TO ACCESS THE VALUE HERE;Initial Catalog=Database;Integrated Security=True;Connect Timeout=15" /></connectionStrings>    

我可以这样做吗?

【问题讨论】:

标签: c#


【解决方案1】:

你总是可以在代码中做这样的事情:

var host = System.Configuration.ConfigurationManager.AppSettings["dbHostAddress"]

var connectionString = System.Configuration.ConfigurationManager.
   ConnectionStrings["ConnectionString"]
  .ConnectionString.Replace("REPLACE_VALUE",host);

您只需使用占位符存储连接字符串,然后将其拉入代码并用您想要的替换占位符值。

Data Source=REPLACE_VALUE;Initial Catalog=Database;
    Integrated Security=True;Connect Timeout=15

然后,我将围绕配置值创建一个包装类,以便在您访问代码中的属性时自动发生这种情况。

【讨论】:

  • 我确定以上方法可行。我希望可以在没有代码的情况下做到这一点。我想我的问题是我是否可以在 xml 中声明和使用变量。连接字符串用例只是一个例子。我还有其他用例可能会更复杂。谢谢
猜你喜欢
  • 2011-05-05
  • 2011-05-14
  • 2013-02-14
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
相关资源
最近更新 更多