How to write relative path to connect Access database with asp.net

伊谢尔伦
Release: 2016-11-25 09:45:11
Original
1806 people have browsed it

When Asp.net connects to the Access database, we usually write the database connection string into the web.config configuration file. The database path in the connection string can only be expressed in the form of an absolute path. If you want to move the program, you must modify the database path of the database connection string in web.config, which is very troublesome. It is also incorrect if it is written in a relative path format such as ~/database/test.mdb. For example:

 <connectionstrings>
    <add name="Access" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0;data source=~/database/test.mdb" providername="System.Data.OleDb" />
  </connectionstrings>
Copy after login

The above is written incorrectly.

There are currently 2 common solutions:

1. By using the DataDirectory keyword method

Starting from Asp.net 2.0, there is an App_Data directory to specifically store data files. It can be used to store Access, SQL Server Express, XML, etc. data file. You can place the Access database file in the App_Data folder, and then 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>
Copy after login

2. Set two strings in the web.config file

Set two strings in the web.config file, one is the driver string and the other is the relative path of the Access database file. When using it, use Server.MapPath() to obtain 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>
Copy after login

When used in the background, the code is as follows:

private string GetConnStr()
{
    string connStr = WebConfigurationManager.ConnectionStrings["Access"].ConnectionString;
    connStr = connStr.Replace("{0}", Server.MapPath(WebConfigurationManager.AppSettings["AccessPath"].ToString()));
    return connStr;
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template