var connection = ConnectionFactory.GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);

这是我的app。config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

但是当我的项目运行时,这是我的错误:

对象引用未设置为对象的实例。


当前回答

string str = Properties.Settings.Default.myConnectionString; 

其他回答

首先,您必须添加System。配置引用到您的项目,然后使用下面的代码获取连接字符串。

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}

您可以使用此方法获取连接字符串

using System; 
using System.Configuration;

private string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;
}

为了从app.cfg(在windows服务应用程序中)读取连接字符串,下面的代码对我有用

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
    connectionStringsSection.ConnectionStrings["CONNECTIONSTR"].ConnectionString = @"New Connection String";

您可以使用下面的代码行获取连接字符串-

using System; using System.Configuration;

var connectionString=ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

这里有一个参考: App.config中的连接字符串