When ASP. NET connects to an Access database, we typically write the database connection string to the Web. config configuration file. The database paths in the connection string can only be represented in absolute paths, so if you want to move the program, you have to modify the database path of the database connection strings in Web. config, which is cumbersome. If written in relative path form such as: ~/database/test.mdb is also incorrect. For example:
<connectionstrings> <add name= "Access" connectionstring= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=~/database/test.mdb "providername=" System.Data.OleDb "/> </connectionstrings>
The above notation is wrong.
There are currently 2 common solutions:
1, by using the DataDirectory keyword method
Starting with ASP. NET 2.0, there is a App_Data directory dedicated to storing data files that can be used to Access,sql Server Express, XML, and other data files. You can put the Access database file in the App_Data folder and use the keyword Datadirectoty to get the path.
<connectionstrings> <add name= "Access" connectionstring= "Provider=Microsoft.Jet.OLEDB.4.0;Data source=| Datadirectory|test.mdb " providername=" System.Data.OleDb "/> </connectionstrings>
2. Set two strings in the Web. config file
Set two strings in the Web. config file, one for the drive string and the other for the relative path to the Access database file. Use Server.MapPath () to get the absolute path, and then the combined connection string can be used.
<connectionStrings> <add name= "Access" connectionstring= "Provider=Microsoft.Jet.OLEDB.4.0;Data source={0} " providername=" System.Data.OleDb "/></connectionstrings><appsettings> <add key= "Accesspath" value= "~/database/test.mdb"/></appsettings>
The following code is used in the background:
private String Getconnstr () { string connstr = webconfigurationmanager.connectionstrings["Access"]. ConnectionString; ConnStr = Connstr.replace ("{0}", Server.MapPath (webconfigurationmanager.appsettings["Accesspath"]. ToString ())); return connstr;}