項目--Asp.net全域變數的設定和讀(web.config 和 Gloab)

來源:互聯網
上載者:User

標籤:tar   檔案   資料   string   art   os   

方法一:web.config檔案
——設定:
在web.config檔案裡添加關鍵字key是通過<appSettings>標記來實現的,但是appSettings標記通常放在<system.web>.....</system.web>標記外面。例: 
<configration> 
<appSettings> 
<add key="connString1" value="server=localhost;user id=sa;pwd=;database=資料庫名字"/> 
<add key="connString2" value="provider=Microsoft.Jet.OleDb.4.0;Data Source=資料庫路徑"/> 
</appSettings> 
<system.web> 
</system.web> 
</configration> 

——讀取:
要在代碼中引用這些資料庫連接字串,需要先添加對System.ConFiguration名字空間的引用,在這個名字空間中含有ConfigurationSettings類,其靜態方法ConfigurationSettings.AppSettings屬性可擷取web.config檔案中<appSettings>節的設定,讀到的值為string型。例如: 

using System.Configuration; 
string conn1 = ConfigurationSettings.AppSettings["connString1"]; 
string conn2 = ConfigurationSettings.AppSettings["connString2"]; 
SQLConnection myConn1 = new SQLConnection(conn1); 
OleDbConnection myConn2 = new OleDbConnection(conn2); 

在VS2005中, ConfigurationSettings.AppSettings 可以換成 ConfigurationManager.AppSettings

方法二:Gloab檔案
 ——設定:
在Global檔案裡中添加 
protected void Session_Start(Object sender, EventArgs e) 

Session["sqlConnectionString"] = "uid=Username;pwd=password;database=MyTest;server=Localhost;Connect Timeout=300"; 


——讀取:
在代碼中的應用: 
String strConnection=Session["sqlConnectionString"].ToString(); 
sqlConnection_1=new SqlConnection(strConnection); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.