Many friends are troubled by the relative path problem of ACCESS database in .net program, which makes them have to modify web.config every time they move the program.
The database path in the database connection string.
Many people write the following in their web.config:
<appSettings>
<add key="OLEDBCONNECTIONSTRING" value="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=E:webApp_DataData.mdb)"></add>
</appSettings>
The program is written like this:
MyConn = new OleDbConnection(System.Configuration.ConfigurationManager.AppSettings["OLEDBCONNECTIONSTRING"]);//Note: ConfigurationSettings are written differently in VS2005 and VS2003. Check the specific differences yourself.
In this way, when the program is running, errors such as the following are often prompted:
'C:WINDOWSsystem32~App_DataData.mdb' is not a valid path. Determine whether the path name is spelled correctly and whether you are connected to the server where the file is stored. Data Source=~App_DataData.mdb
Even if the absolute path is correct, web.config must be modified when transplanting the program, so it is more troublesome.
There are also ways to use Server.MapPath like ASP in web.config to obtain the database path, but web.config does not recognize Server.MapPath, so this method does not work.
Later, through exploration and reference to other programs, I concluded the following method, which can easily transplant the program path without having to modify the ACCESS database path.
What I wrote in web.config is as follows:
<appSettings>
<add key="SQLConnString" value="provider=microsoft.jet.oledb.4.0;data source="/>
<add key="dbPath" value="~/App_Data/mydata.mdb"/>
</appSettings>
In the data access class in the program, I took out "SQLConnString" and "dbPath" and connected them into a string "CONN_STRING_NON_DTC"
public static readonly string CONN_STRING_NON_DTC = System.Configuration.ConfigurationManager.AppSettings["SQLConnString"].ToString() + System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dbPath"]) + ";";
This is the writing method in VS2005. I defined CONN_STRING_NON_DTC as static readonly for ease of use.
Well, this way you can transplant your program at will without caring about the path of the database, once and for all ^_^, suitable for lazy people like me!