我在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();
}
}
}
这些尝试均不会产生连接字符串。 此注释是为了满足Stackoverflow的格式要求。
答案 0 :(得分:0)
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;