C# 从 app.config 获取 ConnectionString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11139226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:39:48  来源:igfitidea点击:

Get ConnectionString from app.config

c#

提问by Daniel Sh.

I'm pretty sure there's some quick and easy error in this code but somehow I've spent the last 2 hours with this and couldn't solve it.

我很确定这段代码中存在一些快速而简单的错误,但不知何故,我在过去的 2 个小时里一直在解决这个问题,但无法解决。

App.config:

App.config

<configuration>
  <connectionStrings>
    <add name="BO"
        connectionString="Data Source=MyServer;Initial Catalog=BO;User ID=WebUser;Password=MyPasswd"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Class.cs:

Class.cs

string connectionString = getNewConnection();
using (SqlConnection conn = new SqlConnection(connectionString)) { code }

Method.

方法。

public static string getNewConnection()
{
   return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
 }

Error:

错误:

Object reference not set to an instance of an object

你调用的对象是空的

on the line :

在线上 :

return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;

EDIT:

编辑:

Error image, the Spanish sentence means: Object reference not set to an instance of an object

错误图片,西班牙语句子的意思是:未将对象引用设置为对象的实例

采纳答案by Andrew Hagner

It should be:

它应该是:

ConfigurationManager.ConnectionStrings["BO"].ConnectionString;

Edit:

编辑:

You will need the corresponding libraries as well if you don't have them yet, as mentioned in the below answers I think its System.Configuration

如果您还没有它们,您也将需要相应的库,如以下答案中所述,我认为它的 System.Configuration

So in full you should have:

所以完整的你应该有:

public static string getNewConnection()
{
    return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
}

回答by etlds

Did you use the WebConfigurationManager?

你使用了 WebConfigurationManager 吗?

string MyConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["BO"].ConnectionString;

回答by ALI VOJDANIANARDAKANI

Use these codes in the Class :

在 Class 中使用这些代码:

class Connection
    {
        public static string con
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            }
        }
    }

回答by daszarrin

Add a reference to System.Configuration.dll, and you should be able to use the System.Configuration.ConfigurationManager.

添加对 System.Configuration.dll 的引用,您应该能够使用 System.Configuration.ConfigurationManager。