从 App.config 获取连接字符串

发布于 2024-11-17 19:30:15 字数 645 浏览 4 评论 0原文

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>

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

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

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

And this is my 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>

But when my project runs this is my error:

Object reference not set to an instance of an object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

酒废 2024-11-24 19:30:15

您可以执行以下操作:

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

您的程序集还需要对 System.Configuration.dll 的引用

You can just do the following:

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

Your assembly also needs a reference to System.Configuration.dll

装纯掩盖桑 2024-11-24 19:30:15

由于这是一个非常常见的问题,我准备了一些 Visual Studio 的屏幕截图,以便通过 4 个简单的步骤轻松理解。

从 app.config 获取连接字符串

Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.

get connection string from app.config

木落 2024-11-24 19:30:15
string str = Properties.Settings.Default.myConnectionString; 
string str = Properties.Settings.Default.myConnectionString; 
謌踐踏愛綪 2024-11-24 19:30:15

另请检查您是否已在引用下包含 System.Configuration dll。如果没有它,您将无法访问 System.Configuration 命名空间中的 ConfigurationManager 类。

Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.

失退 2024-11-24 19:30:15

首先将 System.Configuration 的引用添加到您的页面。

using System.Configuration;

然后根据您的 app.config 获取连接字符串,如下所示。

string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();

现在您已经有了连接字符串并且可以使用它了。

First Add a reference of System.Configuration to your page.

using System.Configuration;

Then According to your app.config get the connection string as follow.

string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();

That's it now you have your connection string in your hand and you can use it.

喵星人汪星人 2024-11-24 19:30:15
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}
夜唯美灬不弃 2024-11-24 19:30:15

试试这个

string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

Try this out

string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
柠檬色的秋千 2024-11-24 19:30:15

这对我有用:

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

输出:

数据源=.;初始目录=OmidPayamak;IntegratedSecurity=True"

This worked for me:

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

Outputs:

Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"

情深缘浅 2024-11-24 19:30:15

这个问题中的OP可能试图在dll中使用App.Config。

在这种情况下,代码实际上是在尝试访问可执行文件的 App.Config,而不是 dll。由于未找到名称,因此返回 Null,因此显示异常。

以下帖子可能会有所帮助:
DLL 的 app.config 中的 ConnectionString 为 null

It is possible that the OP in this question is trying to use an App.Config within a dll.

In this case, the code is actually trying to access the App.Config of the executable and not the dll. Since the name is not found, you get a Null returned, hence the exception shown.

The following post may be helpful:
ConnectionString from app.config of a DLL is null

笔芯 2024-11-24 19:30:15

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

然后当您想要使用连接时,在您的表单中执行此操作:

 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 的,但逻辑是相同的。

1) Create a new form and add this:

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

then when you want to use the connection do this in ur form:

 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()

and thats it. You will be connected to the DB and can do stuff.

This is for vb.net but the logic is the same.

千年*琉璃梦 2024-11-24 19:30:15

你有没有尝试过:

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

Have you tried:

var connection = new ConnectionFactory().GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);
你的呼吸 2024-11-24 19:30:15

我有同样的问题。我的解决方案是由两个项目构建的。一个类库和一个引用该类库项目的网站。问题是我试图访问我的类库项目中的App.config,但系统正在搜索Web.config的网站。我将连接字符串放入 Web.config 中并且...问题解决了!

主要原因是尽管 ConfigurationManager 在另一个程序集中使用,但它正在 runnig 项目内部进行搜索。

I had the same Issue. my solution was built up from two projects. A Class library and a website referencing to the class library project. the problem was that i was trying to access the App.config in my Class library project but the system was searching in Web.config of the website. I put the connection string inside Web.config and ... problem solved!

The main reason was that despite ConfigurationManager was used in another assembly it was searching inside the runnig project .

情愿 2024-11-24 19:30:15

上面的答案没有详细说明connectionStrings索引中的值来自哪里。

如上所述,要获取连接字符串,您可以说:

string conStr = ConfigurationManager.ConnectionStrings["XXX"].ToString();

要使用 XXX 的正确值,请转到主项目 web.config 文件并查找以下内容代码:

<connectionStrings>
    <add name="Authentication" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Authentication;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Authentication.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

其中显示 name= ,这些引号中的文本是您在上面的代码中使用的 XXX 的值。在我上面的示例中,它恰好是身份验证

The answers above didn't elaborate where the value in connectionStrings index comes from.

As mentioned above, to get your connection string, you say:

string conStr = ConfigurationManager.ConnectionStrings["XXX"].ToString();

To use the correct value of XXX, go to your main projects web.config file and look for the following piece of code:

<connectionStrings>
    <add name="Authentication" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Authentication;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Authentication.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

Where it says name= , the text within those proceeding quotes is the value of XXX you use in the code above. In my example above, it happens to be Authentication

虐人心 2024-11-24 19:30:15
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
墨离汐 2024-11-24 19:30:15

问题似乎不在于引用,您将连接字符串设置为空,因此请确保您已将值添加到正在运行的项目的配置文件中,这意味着首先启动/执行的主程序/库。

It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.

握住我的手 2024-11-24 19:30:15

首先,您必须向项目添加 System.Configuration 引用,然后使用以下代码获取连接字符串。

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();

First you have to add System.Configuration reference to your project and then use below code to get connection string.

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
路弥 2024-11-24 19:30:15

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

using System; 
using System.Configuration;

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

You can use this method to get connection string

using System; 
using System.Configuration;

private string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;
}
悟红尘 2024-11-24 19:30:15

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

using System; using System.Configuration;

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

这是参考:
连接来自 App.config 的字符串

You can fetch the connection string by using below line of code -

using System; using System.Configuration;

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

Here is a reference :
Connection String from App.config

本宫微胖 2024-11-24 19:30:15

我引用了 System.Configuration 库,并且出现了相同的错误。
调试文件没有 app.config,请手动创建此文件。
错误是,我通过在调试文件夹中复制文件“appname.exe.config”解决了这个问题。 IDE 未创建该文件。

I referenced System.Configuration library and I have the same error.
The debug files had not their app.config, create manually this file.
The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.

白云悠悠 2024-11-24 19:30:15

我通过使用索引读取字符串并逐一检查来解决该问题。使用名称读取仍然会出现相同的错误。
我在开发 C# 窗口应用程序时遇到问题,但在我的 asp.net 应用程序中没有遇到问题。环境中一定有什么地方不对劲。

I solved the problem by using the index to read the string and checking one by one. Reading using the name still gives the same error.
I have the problem when I develop a C# window application, I did not have the problem in my asp.net application. There must be something in the setting which is not right.

梦途 2024-11-24 19:30:15

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

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

In order to read the connection string from app.cfg (in windows service application) the below code worked for me

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
    connectionStringsSection.ConnectionStrings["CONNECTIONSTR"].ConnectionString = @"New Connection String";
二智少女 2024-11-24 19:30:15

UserControl 的构造函数中放置 ConfigurationManager.ConnectionStrings 时遇到此问题,这里的解决方案都不适合我。

经过一番研究,在尝试从 DesignTime 访问它时,ConfigurationManager.ConnectionStrings 似乎将为 null。

这篇文章中,我想出了以下代码来检测DesignTime作为解决方法问题:

public class MyUserControl : UserControl 
{
    ....
    public MyUserControl ()
    {
        InitializeComponent();

        bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
        if (!designMode)
        {
            this.connectionString = 
                ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
        }
    }
}

Encountered this issue while placing ConfigurationManager.ConnectionStrings in UserControl's constructor, and none of the solution here worked for me.

After some research, seems like ConfigurationManager.ConnectionStrings would be null while trying to access it from the DesignTime.

And from this post, I came up with this following code to detect DesignTime as a workaround to the issue:

public class MyUserControl : UserControl 
{
    ....
    public MyUserControl ()
    {
        InitializeComponent();

        bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
        if (!designMode)
        {
            this.connectionString = 
                ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
        }
    }
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文