使用Visual Studio新增主控台應用程式是不會有Web.Config,請問有沒有辦法主控台應用程式引用Web.config的連線字串呢?謝謝
能
web.config (appSettings 區段通常放在 connectionStrings 區段的上面)
<appSettings>
<add key="WebName" value="This is MyWeb" />
</appSettings>
using System.Web.Configuration; //WebConfigurationManager的命名空間必須
//抓 AppSettings 範例
string strWebName = WebConfigurationManager.AppSettings["WebName"];
//抓 ConnectionString 範例
string strConnString = WebConfigurationManager.ConnectionStrings["MyDBConnString"]
主控台應用程式只有app.config
<app.config>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="DB"
connectionString="Data Source=xxx;Initial Catalog=MyLab;User ID=user;password=pass"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="cKey" value="xyz123" />
</appSettings>
</configuration>
<引用方式>
class Program
{
public static string connstr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
public static string cKey = ConfigurationManager.AppSettings["cKey"];
static void Main(string[] args)
{
}
}