c# - 从 Appsettings app.config 文件调用连接字符串到 C# 代码

标签 c# xml app-config

我正在尝试将连接字符串从 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 始终为空并且没有获取连接字符串。 错误是“对象引用未设置到对象的实例”。

最佳答案

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

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

然后

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

关于c# - 从 Appsettings app.config 文件调用连接字符串到 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10731482/

相关文章:

c# - SQL加密字符串的解密

c# - 在 Json.Net 中获取 JObject 的名称

C# BitmapFrame.Thumbnail 属性对于某些图像为 null

xml - Vim 中的模式感知 XML 编辑

javascript - 为什么我得到一个 {"location": null} when I try to convert a text/xml into an object?

C# 应用程序配置文件

c# - 带有 App.config 文件的 SQL Server 外部的 connectionString

c# - 从 C# 传输到 ExtJS 时 JSON 数据发生变化

html - 将 xmllint 和 xpath 用于不太完美的 HTML 文档?

c# - 在 Exe 文件中嵌入 ConfigFile