“ConfigurationManager”这个名称在当前上下文中不存在。

3

大家好,我遇到了以下错误:“当前上下文中不存在 'ConfigurationManager' 的名称”。

// namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace Database1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static string GetConnectionString(string strConnection)
        {
            //variable to hold our connection string for returning it

            string strReturn = "";
            //check to see if the user provided a connection string name
            //this is for if your application has more than one connection string

            if (!string.IsNullOrEmpty(strConnection)) //a connection string name was        
            {
                //get the connection string by the name provided
                strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;

            }
            else //no connection string name was provided
            {
                //get the default connection string
                strReturn = ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
            }
            //return the connection string to the calling method
            return strReturn;
        }

    }
}
5个回答

12

你是否已经添加了对 System.Configuration.dll 的引用?


我没有添加这个引用,也无法在“添加引用”选项卡中找到它,该如何找到它? - user1312412
不确定,但在这种情况下,消息应该是“找不到类型或命名空间'ConfigurationManager'”,对吗? - V4Vendetta
你使用的是哪个版本的Visual Studio和.NET Framework? - Joshua

6

您需要添加对System.Configuration.dll的引用

右键单击并点击“添加引用”按钮

在打开的弹出窗口中,点击“.Net”选项卡

您应该能够找到System.Configuration.dll文件


1
不,它不在那里。我已经尝试过了,但是在这个选项卡中找不到System.Configuration.dll文件。 - user1312412
奇怪,你在那里找不到它吗?也许你需要重新启动VS。 - V4Vendetta

3
这是路径:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Configuration.dll

您还可以在:System:中添加引用。

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Configuration.Install.dll

希望能帮到你:)

1

我在使用 .Net Core 时遇到了同样的问题,但是在程序包管理器中运行 Install-Package System.Configuration.ConfigurationManager 解决了我的问题。


1

我使用了 .NET Core,在我的情况下也无法解决,求帮助。 - P Rane
2012年还没有.NET Core,所以这个答案肯定不适用于它。使用Google搜索很容易就能找到正确的答案。 - Lex Li

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接