如何从 App.config 中检索连接字符串 [重复]
Posted
技术标签:
【中文标题】如何从 App.config 中检索连接字符串 [重复]【英文标题】:How to retrieve connection strings from App.config [duplicate] 【发布时间】:2019-08-17 10:19:18 【问题描述】:我在 Windows 窗体应用程序中有以下配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConsoleApp1.Properties.Settings.abcdConnectionString"
connectionString="Data Source=xxx.yyy.org;Initial Catalog=MyCatalog;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
以下代码多次尝试检索连接字符串。 没有任何效果。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
namespace ConsoleApp1
class Program
static void Main(string[] args)
NameValueCollection sAll;
sAll = ConfigurationManager.AppSettings;
Console.Write("[");
foreach (string s in sAll.AllKeys)
Console.Write(">>");
Console.WriteLine("Key: " + s + "Value: " + sAll.Get(s));
Console.Write("]");
Console.ReadLine();
Console.Write("sAll = (");
Console.Write(sAll);
Console.WriteLine(") end of sALL");
Console.ReadLine();
string keyvalue =
System.Configuration.ConfigurationManager.AppSettings["ConsoleApp1.Properties.Settings.abcdtest19ConnectionString"];
Console.WriteLine("keyvalue = (" + keyvalue + ")");
Console.ReadLine();
keyvalue = ConfigurationManager.AppSettings["ConsoleApp1.Properties.Settings.abcdConnectionString"];
Console.WriteLine("keyvalue = (" + keyvalue + ")");
Console.ReadLine();
keyvalue = ConfigurationManager.AppSettings["abcdConnectionString"];
Console.WriteLine("keyvalue = (" + keyvalue + ")");
Console.ReadLine();
这些尝试都不会产生连接字符串。 此注释是为了满足 *** 的格式要求。
【问题讨论】:
谢谢。我遇到的问题是在引用时依赖 Telesense 【参考方案1】:string constr = System.Configuration.ConfigurationManager.
ConnectionStrings["ConsoleApp1.Properties.Settings.abcdConnectionString"].ConnectionString;
如果您像这样更改您的 app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="abcdConnectionString"
connectionString="Data Source=xxx.yyy.org;Initial Catalog=MyCatalog;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
然后
string constr = System.Configuration.ConfigurationManager.
ConnectionStrings["abcdConnectionString"].ConnectionString;
【讨论】:
谢谢。这行得通。我遇到的问题是在引用 System.Configuration 的引用之前依赖 Telesense。以上是关于如何从 App.config 中检索连接字符串 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
C# ConfigurationManager 从 app.config 检索错误的连接字符串
如何从加载的 App.config 文件中检索 ApplicationSettings?
Azure 函数 - 如何在 app.config 中添加我的数据库连接字符串