【问题标题】:Calling Connection string from App setings app.config file to C# code从 App 设置 app.config 文件调用连接字符串到 C# 代码
【发布时间】:2023-03-13 17:09:01
【问题描述】:

我正在尝试将连接字符串从 app.config 文件调用到 C# 代码。这是 app.config 代码:

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
 <appSettings>

<add key="connectstring" value="Data Source=server111;Initial Catalog=database1;        Integrated Security=False;Persist Security Info=False; User ID=username;Password=password;Encrypt=True; TrustServerCertificate=True; MultipleActiveResultSets=True"/>

 </appSettings>
</configuration>

这是 C# 代码:

  private SqlConnection connStudent;  
  connStudent = new SqlConnection(ConfigurationManager.AppSettings["connectstring"].ToString());
  connStudent.Open();

代码应该是正确的,但是我得到一个空引用异常,并且在调试程序时,connStudent 始终为空并且没有得到连接字符串。 错误是“对象引用未设置为对象的实例”。

【问题讨论】:

  • 我认为这不能解决您的问题,但我相信 app.config 中的“值”已经作为字符串返回,因此不需要 ToString()。
  • 您显示的 C# 代码不可编译甚至无效,因此至少提供异常的完整堆栈跟踪,以便更好地确定它“可能”出现的位置。到目前为止,很可能在您的 appSettings 中找不到“connectstring”,因此AppSettings["connectstring"] 返回null。因此,请确保您的 app.config 文件实际上是“构建到”输出目录中,在您的可执行文件旁边,具有相同的名称(如“my.exe.config”)。

标签: c# xml app-config


【解决方案1】:

如果您使用的是 .NET 2.0 或更高版本,请使用以下

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

然后

string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

【讨论】:

  • 为什么对 .NET 3.5+ 有限制? ConfigurationManager.ConnectionStrings 属性自 .NET 2.0 起可用。
  • 仍然为空。对象引用未设置为对象的实例。
  • 你添加了 ref 到 System.Configuration 吗?
【解决方案2】:

您的代码很好。检查以确保您的copy to output directory 属性设置为copy alwayscopy if newer。如果这仍然不起作用,请尝试删除 temp obj 文件。

以下测试代码运行良好。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="connectstring" value="Data Source=server111;Initial Catalog=database1;        Integrated Security=False;Persist Security Info=False; User ID=username;Password=password;Encrypt=True; TrustServerCertificate=True; MultipleActiveResultSets=True"/>
  </appSettings>
</configuration>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection connStudent;
                connStudent = new SqlConnection(ConfigurationManager.AppSettings["connectstring"].ToString());
                //connStudent.Open();
                //connStudent.Close();
                Console.WriteLine("ok");
            }
            catch
            {
                Console.WriteLine("error");
            }
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2015-01-10
    • 2023-04-04
    • 2015-01-31
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多