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
Get ConnectionString from app.config
提问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:
编辑:


采纳答案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。

