web.config access資料庫相對路徑設定方法 for asp.net2.0
2006-12-19 15:21
今天剛巧自己碰到了在web.config設定connectionStrings的問題, 翻了好些書, 只都說sql的設定方法,唯獨破access被人遺忘到角落:那是隻字未提啊~~
幸好,在visual studio 2005協助檔案裡面有提及一些:
<connectionStrings>
<add name="MyJetConn" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\testdatasource.mdb; Persist Security Info=False;" providerName="System.Data.OleDb" />
</connectionStrings>
經過測試,這樣設定是可以的,但是要放到租用的伺服器上面是運行不了的,我需要的是相對路徑的設定方法,在c#中雖然可以用 ~ 代替當前路徑,可是運行後發現,當前路徑在windows\system32\ 那是絕對不行的.
在網上發現有人用了特殊字元代替相對路徑,然後在頁面的後台代碼中引用該字串的時候用Server.MapPath()來代替那個特殊字元! 這個確實是一種好方法!不過還有更好的,就是ApplicationDeployment.DataDirectory----This property is new in the .NET Framework version 2.0.
最好的方法:
web.config配置
<configuration>
<appSettings/>
<connectionStrings>
<add name="MyJetConn" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|\atm.mdb; Persist Security Info=False;" providerName="System.Data.OleDb" />
</connectionStrings>
...
測試程式
public string OpenDB()
{
string msg;
OleDbConnection MyOleDB = new OleDbConnection();
MyOleDB.ConnectionString = WebConfigurationManager.ConnectionStrings["MyJetConn"].ConnectionString;
try
{
MyOleDB.Open();
msg = "server vision:" + MyOleDB.ServerVersion + "connection is " + MyOleDB.State.ToString();
return (msg);
}
catch (Exception err)
{
msg = err.Message;
return (msg);
}
finally {
MyOleDB.Close();
}
}
輸出:
server vision:04.00.0000connection is Open
補充說明:網站的代碼的檔案夾至少為iis虛擬目錄的根目錄,否則用本機http調試的時候會出現問題.
比如:
Line 26: ASP.NET to identify an incoming user.
Line 27: -->
Line 28: <authentication mode="Forms" />
Line 29: <!--
Line 30: The <customErrors> section enables configuration
ok,問題解決了,心情好多了,大家共用!