直接配置文件连接ASP.NET数据库相对路经解决方案:
MS SQL连接:
<connectionStrings>
<add name="db" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\test.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
Access连接:
<connectionStrings>
<add name="ConnStr_Access" providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\cms.mdb;"/>
</connectionStrings>
|DataDirectory|会被自动解析到App_Data
下面是MSDN的说明:
使用 DataDirectory 替代字符串
AttachDbFileName 已在 ADO.NET 2.0 中进行了扩展,引入了 |DataDirectory|(包含在管道符号中)替代字符串。DataDirectory 与 AttachDbFileName 结合使用可指示数据文件的相对路径,允许开发人员创建基于数据库源的相对路径(而无需指定完整路径)的连接字符串。
DataDirectory 点的物理位置取决于应用程序的类型。 在此示例中,要附加的 Northwind.mdf 文件位于应用程序的 \app_data 文件夹中。
![直接配置文件连接ASP.NET数据库相对路经解决方案 - 一滴清水 - one world one blog](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![直接配置文件连接ASP.NET数据库相对路经解决方案 - 一滴清水 - one world one blog](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![直接配置文件连接ASP.NET数据库相对路经解决方案 - 一滴清水 - one world one blog](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![直接配置文件连接ASP.NET数据库相对路经解决方案 - 一滴清水 - one world one blog](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
使用 DataDirectory 时,目录结构中的结果文件的路径不能高于替代字符串指向的目录。 例如,如果完全展开的 DataDirectory 为 C:\AppDirectory\app_data,则上面显示的示例连接字符串有效,因为它在 c:\AppDirectory 之下。 但是,如果尝试将 DataDirectory 指定为 |DataDirectory|\..\data,将会产生一个错误,因为 \data 不是 \AppDirectory 的子目录。