【问题标题】:configurationManager does not exist in the namespace System.Configuration命名空间 System.Configuration 中不存在 configurationManager
【发布时间】:2012-12-06 02:46:03
【问题描述】:

我已使用以下命名空间将我的项目连接到 sql server:

using System.Configuration;

也用过

string str=System.Configuration.ConfigurationSettings.AppSettings["myconnection"];
SqlConnection oconnection = new SqlConnection(str);
oconnection.Open();

当我运行程序时,出现错误并显示消息

'System.Configuration.ConfigurationSettings.AppSettings' 是 已过时。此方法已过时,已被替换为 '系统配置! System.Configuration.ConfigurationManager.AppSettings '

但我在该命名空间中没有找到 ConfigurationManager,对于 oconnection.Open();,消息是

无效操作异常

未处理。

我能做什么?

【问题讨论】:

  • System.Configuration.ConfigurationSettings.AppSettings 已被替换 - 您应该改用 System.Configuration.ConfigurationManager.AppSettings(如消息所述)。您可能需要添加对 System.Configuration 程序集的引用。至于尝试打开 SqlConnection 时的异常,我建议记录完整的异常(消息 + 堆栈跟踪)-以获取更多信息。

标签: c# sql-server visual-studio-2005


【解决方案1】:

转到引用,并添加对System.Configuration的引用

完成此操作后,您应该可以引用System.Configuration.ConfigurationManager

string str = System.Configuration.ConfigurationManager.AppSettings["myconnection"];
SqlConnection oconnection = new SqlConnection(str);
oconnection.Open();

来自 MSDN: ConfigurationManager 类使您能够访问机器、应用程序和用户配置信息。此类替换了已弃用的 ConfigurationSettings 类。

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx


编辑:附加信息

参考InvalidOperationException。这是在连接字符串未指定数据源或服务器时引起的。我猜你的连接字符串是空的。

在您的 web.config 中检查您的连接字符串的位置。如果它属于该元素,那么您需要将代码更改为搜索 ConnectionStrings 而不是 AppSettings

string str = System.Configuration.ConfigurationManager.
    ConnectionStrings["myconnection"].ConnectionString;

【讨论】:

  • 兄弟感谢您的建议。但是没有ConfigurationManager。我根据您的建议完成了。再次感谢
  • 您确定您已将引用添加到 System.Configuration 程序集吗?许多项目类型不会加载此引用,您必须手动完成
  • 感谢 Jeffery Khan,我有 ConfigurationManager。但发现另一个问题。问题出在 oconnection.Open();并且消息是 InvalidOperationException 未处理(实例失败)。请亲爱的,再次帮助我。再次感谢您的热情
  • 这个解决方案也适用于我的情况,谢谢,Khan!
【解决方案2】:

如果您在解决方案中有多个项目,则必须将引用 System.Configuration 添加到每个项目中,ConfigurationManager 才能在其中任何一个项目中工作。

【讨论】:

  • 哇,这很奇怪……但这是正确的答案。
  • 在我找到这个答案之前一直在拉我的头发。谢谢!
  • 为什么这在文档中没有突出显示?叹息...但是非常感谢您的解决方案。
【解决方案3】:

在你的项目中添加 System.Configuration.dll 的引用,然后 ConfigurationManager 将可用

【讨论】:

    【解决方案4】:

    从 nuget 包安装 System.Configuration。 然后添加引用。

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2011-10-19
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多