Answers:
C#
// Add a using directive at the top of your code file
using System.Configuration;
// Within the code body set your variable
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
VB
' Add an Imports statement at the top of your code file
Imports System.Configuration
' Within the code body set your variable
Dim cs as String = ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString
我猜您需要添加对System.Configuration程序集的引用(如果尚未添加)。
另外,您可能需要在代码文件的顶部插入以下行:
using System.Configuration;
在VB
:这应该工作
ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
在C#
其中(根据Ala的评论)
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
C#
string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
在WEB.CONFIG下面的文件代码
<connectionStrings>
<add name="ABCD" connectionString="Data Source=DESKTOP-SU3NKUU\MSSQLSERVER2016;Initial Catalog=TESTKISWRMIP;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
在上面的代码ABCD中是连接名称
for
循环(for (int i = 0; i < numOfConnections; i++) { var conn = ConfigurationManager.ConnectionStrings[i]; ... }
)中读取所有连接字符串并使它们在组合框中可供选择,则这很有用。使用var numOfConnections = ConfigurationManager.ConnectionStrings.Count;
可以确定存在多少个连接字符串。在此示例中conn.Name
包含连接的名称。
您必须在页面或类的顶部调用该类:
using System.Configuration;
然后,您可以使用此方法返回准备好传递给sqlconnection对象的连接字符串,以继续进行工作,如下所示:
private string ReturnConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DBWebConfigString"].ConnectionString;
}
为了清楚起见,这是Web Config中的值:
<add name="DBWebConfigString" connectionString="....." /> </connectionStrings>
using System.Configuration;
string connString = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();
切记不要使用ConnectionStrings [index],因为您可能具有全局计算机配置和可移植性
System.Configuration.dll
。