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,问题解决了,心情好多了,大家共享!
转载于:https://www.cnblogs.com/twttafku/archive/2008/07/10/1240090.html