【问题标题】:How to read <connectionstring> of web.config from a console application?如何从控制台应用程序中读取 web.config 的 <connectionstring>?
【发布时间】:2012-01-24 06:13:52
【问题描述】:

我有 VB.net 控制台应用程序。我想从 web.config 中读取 (ConnectionString)。

Web.config 位于我的虚拟 PC 中的特定路径,例如 "C:/mywebConfig"

<add name="MY_DB" connectionString="Data Source=DATASOURCE;Initial Catalog=DB;Persist 

Security Info=False; User ID=***;Password=****;" providerName="System.Data.SqlClient" />

我的代码:

Dim connString As String = String.Empty

connString = ConfigurationManager.ConnectionStrings("MY_DB").ConnectionString

每当我尝试访问它时,我都会收到未设置为对象实例或类似内容的错误 :)

请帮忙。

我尝试在我的项目中添加 web.config,但仍然收到错误。

【问题讨论】:

    标签: .net vb.net web-config connection-string app-config


    【解决方案1】:

    如果您确实想阅读另一个(网络)应用的app.configweb.config,请查看ConfigurationManager.OpenMappedExeConfiguration

    【讨论】:

      【解决方案2】:

      正如 Matt 建议的控制台应用程序,您需要包含一个 app.config 文件。为了便于阅读该文件,您可以引用 System.Configuration 程序集,然后使用 System.Configuration.ConfigurationManager.ConnectionStrings 属性。

      例如:

      string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbconnectionString"].ConnectionString;
      

      编辑

      我刚刚重新阅读了您的帖子,最好检查您的应用是否有权从 c:\ 驱动器读取 .config 文件。

      【讨论】:

        【解决方案3】:

        web.config 用于 Web 应用程序 - 您需要一个 app.config 文件。

        查看此链接了解不同之处:

        dotNET - app.config and web.config

        还有这个堆栈溢出问题what is app.config for

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-05
          • 1970-01-01
          • 2014-05-18
          • 1970-01-01
          • 2023-04-03
          • 2015-08-17
          • 1970-01-01
          相关资源
          最近更新 更多