我在web.config中有以下设置,作为配置元素的子项:
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
在我希望检索连接字符串的代码中,我放置了:
using System.Configuration
...
var connStringObject = ConfigurationManager.ConnectionStrings["GingerlimeDB"];
string connectionString = connStringObject.ConnectionString;
Console.WriteLine(connectionString);
我没有进入控制台输出,而是显示:
对象引用未设置为对象的实例。
如何从Web配置中获取连接字符串?
答案 0 :(得分:1)
假设您的web.config
文件如下所示:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
我使用几乎相同的东西:
using System.Configuration;
....
internal bool OpenDatabaseConnection()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
dbConnection = new SqlCeConnection(connectionString);
dbConnection.Open();
return true;
}
catch (SqlCeException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (InvalidOperationException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ArgumentException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ConfigurationErrorsException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
return false;
}
哪一行实际导致NullReference异常? (对象未设置为对象的实例)?