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 abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

其他回答

1)创建一个新表单并添加以下内容:

Imports System.Configuration
Imports Operaciones.My.MySettings

Public NotInheritable Class frmconexion

    Private Shared _cnx As String
    Public Shared Property ConexionMySQL() As String
        Get
            Return My.MySettings.Default.conexionbd
        End Get
        Private Set(ByVal value As String)
            _cnx = value
        End Set
    End Property

End Class

然后当你想要使用连接时,在ur表单中这样做:

 Private Sub frmInsert_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim cn As New MySqlConnection(frmconexion.ConexionMySQL)
cn.open()

就是这样。您将连接到数据库,并可以做一些事情。

这是vb.net,但逻辑是相同的。

这招对我很管用:

string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

输出:

数据源=.;初始目录=OmidPayamak;集成安全性=True"

string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;

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

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";