我正在使用此代码从我的app.config文件中读取连接字符串,但它始终返回null值。我的App.config文件在我的项目下。这两种方法都是空值:
public SqlConnection getConnection()
{
try
{
// connectionString = ConfigurationManager.AppSettings["dbConn"];
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection = new SqlConnection(connectionString);
}
catch (Exception ex)
{
}
return sqlConnection;
}
这是我的app.config文件声明:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
</configuration>
最佳答案
你能试一下吗
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
<appSettings>
<add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</appSettings>
</configuration>
然后使用第二种方法。
确保在解决方案资源管理器中选择App.Config文件,然后在属性窗口中选择
Copy to Output Directory
到Copy Always
。现在,构建应用程序,然后重试。关于c# - 如何通过C#从App.config文件读取连接字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9859510/