如何通过C#从App.config文件中读取连接字符串

时间:2012-03-25 10:36:47

标签: c# .net c#-4.0

我正在使用此代码从我的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>

4 个答案:

答案 0 :(得分:5)

我认为你试图读取连接字符串两次的问题,首先你做对了,第二次做错了,所以只需删除第二行:

connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString); 

ConfigurationManager.AppSettings用于访问配置的<appSettings>...</appSettings>部分。

答案 1 :(得分:4)

你可以试试吗

<?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 DirectoryCopy Always。现在构建应用程序并重试。

See the screenshot

答案 2 :(得分:1)

您可以在一个类中简单地定义连接字符串并调用该字符串.....

public class Connection
    {
        /// <summary>
        /// Connection String
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
            }
        }
    }

//Returning connction string
 sqlConnection conn = new SqlConnection(Connection.ConnectionString);  

答案 3 :(得分:1)

connectionString=global::myProject.Properties.Settings.Default.myConnectionString